513. 找树左下角的值
本题使用递归解法更为简单
在使用递归时需要注意使用队列当前长度作为循环次数
(不需要添加null进行层数的分隔)
同时对每层的第一个节点进行数值更新 (对应for loop中的index = 0)
public int findBottomLeftValue(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
int res = root.val;
queue.offer(root);
while(!queue.isEmpty()){
int n = queue.size();
for (int i = 0; i < n; i++){
TreeNode node = queue.poll();
if (i == 0) res = node.val;
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
}
return res;
}
112. 路径总和
自己的做法是基于回溯法求出所有path sum,存储在一个集合中
之后判断targetSum是否在集合里
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
List<Integer> path = new ArrayList<>();
HashSet<Integer> set = new HashSet<>();
backtracking(root, set, path);
return set.contains(targetSum);
}
private void backtracking(TreeNode root, HashSet<Integer> set, List<Integer> path){
path.add(root.val);
if (root.left == null && root.right == null){
set.add(findPathSum(path));
return ;
}
if (root.left != null){
backtracking(root.left, set, path);
path.remove(path.size() - 1);
}
if (root.right != null){
backtracking(root.right, set, path);
path.remove(path.size() - 1);
}
}
private int findPathSum(List<Integer> path){
int sum = 0;
for (int val: path) sum += val;
return sum;
}
回溯时间复杂度超过多项式时间
改进为在每一层递归之前从targetSum中减去当前节点值,研究最后一层的叶子节点的值是否等于剩下的targetSum的值 (对于一个节点,该等式只需对一个子节点成立即可返回 true)
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
if (root.left == null && root.right == null) return root.val == targetSum;
return hasPathSum(root.left, targetSum - root.val)
|| hasPathSum(root.right, targetSum - root.val);
}
此方法时间复杂度为O(n)
106. 从中序与后序遍历序列构造二叉树
还没整明白