404.左叶子之和
感觉就是遍历,遇到叶子结点就累加,试了下居然过了
class Solution {int sum = 0;public int sumOfLeftLeaves(TreeNode root) {add(root);return sum;}void add(TreeNode root){if (root == null) return;if (root.left != null && root.left.left == null && root.left.right == null) sum+=root.left.val;if (root.left != null) add(root.left);if (root.right != null) add(root.right);}
}
但是分析了下发现,用全局变量绕开了递归的返回值的处理,于是按照传统二叉树递归逻辑重新分析:
由于要在遍历所有左叶子之后返回总和,因此需要后序遍历
最后sum需要把当前节点和左右部分的和加上并向上return来实现累加
class Solution {public int sumOfLeftLeaves(TreeNode root) {if (root == null) return 0;int leftValue = sumOfLeftLeaves(root.left); // 左int rightValue = sumOfLeftLeaves(root.right); // 右int midValue = 0;if (root.left != null && root.left.left == null && root.left.right == null) { midValue = root.left.val;}int sum = midValue + leftValue + rightValue; // 中return sum;}
}
513.找树左下角的值
这题显然需要层序遍历来确定最后一层,当层的第一个节点就是最左边的节点
class Solution {public int findBottomLeftValue(TreeNode root) {Deque<TreeNode> q = new LinkedList<>();int res = root.val;q.offer(root);while(!q.isEmpty()) {int size = q.size();for (int i = 0; i < size; i++) {TreeNode cur = q.poll();if (i == 0) res = cur.val;if (cur.left != null) q.offer(cur.left);if (cur.right != null) q.offer(cur.right);}}return res;}
}
112. 路径总和
这个题看似跟之前找所有路径的题目很像,但做起来发现简单很多,因为不用回溯
由于从根节点往下遍历到叶子,采用前序遍历
这种找累加和的处理可以一直减,然后跟一个现成的0来比较
class Solution {public boolean hasPathSum(TreeNode root, int targetSum) {if (root == null) return false;return hasPath(root, targetSum);}private boolean hasPath(TreeNode node, int targetSum) {if (node == null) return false;targetSum -= node.val;if (node.left == null && node.right == null) return targetSum == 0;return hasPath(node.left, targetSum) || hasPath(node.right, targetSum);}
}