1. 计算布尔二叉树的值(medium)
二叉树要想到用递归
题目解析

算法原理


代码
class Solution {
public boolean evaluateTree(TreeNode root) {
if (root.left == null)
return root.val == 0 ? false : true;
boolean left = evaluateTree(root.left);
boolean right = evaluateTree(root.right);
return root.val == 2 ? left | right : left & right;
}
}
2.求根节点到叶节点数字之和
题目解析

算法原理

代码
class Solution {
public int sumNumbers(TreeNode root) {
return dfs(root, 0);
}
public int dfs(TreeNode root, int preSum) {
preSum = preSum * 10 + root.val;
if (root.left == null && root.right == null)
return preSum;
int ret = 0;
if (root.left != null)
ret += dfs(root.left, preSum);
if (root.right != null)
ret += dfs(root.right, preSum);
return ret;
}
}
3. 二叉树剪枝(medium)
题目解析

算法原理

代码
class Solution {
public TreeNode pruneTree(TreeNode root) {
if (root == null)
return null;
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if (root.left == null && root.right == null && root.val == 0)
root = null;
return root;
}
}
4. 验证二叉搜索树
题目解析

算法原理

策略二:剪枝

代码
class Solution {
long prev = Long.MIN_VALUE;
public boolean isValidBST(TreeNode root) {
if (root == null)
return true;
boolean left = isValidBST(root.left);
// 剪枝
if (left == false)
return false;
boolean cur = false;
if (root.val > prev)
cur = true;
if (cur == false)
return false;
prev = root.val;
boolean right = isValidBST(root.right);
return left && cur && right;
}
}
5. 二叉搜索树中第 k 小的元素(medium)
题目解析

算法原理

利用了剪枝的策略
代码
class Solution {
int count;
int ret;
public int kthSmallest(TreeNode root, int k) {
count = k;
dfs(root);
return ret;
}
void dfs(TreeNode root) {
if (root == null || count == 0)
return;
dfs(root.left);
count--;
if (count == 0)
ret = root.val;
if (count == 0)
return;
dfs(root.right);
}
}
6. 二叉树中的所有路径
题目解析

算法原理

代码
class Solution {
List<String> ret;
public List<String> binaryTreePaths(TreeNode root) {
ret = new ArrayList<>();
dfs(root, new StringBuffer());
return ret;
}
void dfs(TreeNode root, StringBuffer _path) {
StringBuffer path = new StringBuffer(_path);
path.append(Integer.toString(root.val));
if (root.left == null && root.right == null) {
ret.add(path.toString());
return;
}
path.append("->");
if (root.left != null)
dfs(root.left, path);
if (root.right != null)
dfs(root.right, path);
}
}


174

被折叠的 条评论
为什么被折叠?



