赞
踩
思路:
分别计算一个节点的左子树和右子树是否平衡
如果不平衡则直接返回-1,否则向上层继续递归
最后比较根节点的左右子树是否构成平衡
- public boolean isBalanced(TreeNode root) {
- return getHeight(root) != -1;
- }
-
- private int getHeight(TreeNode root){
- if (root == null) return 0;
- int left = getHeight(root.left);
- if (left == -1) return -1;
- int right = getHeight(root.right);
- if (right == -1) return -1;
- if (Math.abs(left - right) > 1) return -1;
- return Math.max(left, right) + 1;
- }
使用回溯法的注意事项:
先判断当前节点是否是路径的末尾节点 (通过root.left == null && root.right == null判断)
之后对左右子树递归拓展路径,需要注意递归后需要使用path.remove(path.size() - 1)回溯
- public List<String> binaryTreePaths(TreeNode root) {
- List<String> res = new ArrayList<>();
- if (root == null) return res;
- List<Integer> path = new ArrayList<>();
- backtracking(root, res, path);
- return res;
- }
-
- private void backtracking(TreeNode root, List<String> res, List<Integer> path){
- path.add(root.val);
- if (root.left == null && root.right == null){
- res.add(pathToString(path));
- return ;
- }
- if (root.left != null){
- backtracking(root.left, res, path);
- path.remove(path.size() - 1);
- }
- if (root.right != null){
- backtracking(root.right, res, path);
- path.remove(path.size() - 1);
- }
- }
-
- private String pathToString(List<Integer> path){
- StringBuilder sb = new StringBuilder();
- for (int n: path) sb.append(n + "->");
- return sb.toString().substring(0, sb.length() - 2);
- }
思路:使用一个flag来标记当前节点为左或右节点
当一个节点为叶子并且为左叶子,sum加上当前节点的值
- int sum = 0;
-
- public int sumOfLeftLeaves(TreeNode root) {
- if (root == null) return 0;
- dfs(root, false);
- return sum;
- }
-
- private void dfs(TreeNode root, boolean isLeft){
- if (root == null) return;
- if (isLeft && root.left == null && root.right == null) sum += root.val;
- dfs(root.left, true);
- dfs(root.right, false);
- }
另解:使用
root.left != null && root.left.left == null && root.left.right == null
不断更新左叶子的值
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。