110. Balanced Binary Tree
- 思路
- 后续遍历,如果遇到
- Math.abs(leftchildren - rightchildren) >1 return -1
- 任何一个child为-1了,直接返回-1
- 后续遍历,如果遇到
-
java class Solution { public boolean isBalanced(TreeNode root) { return getHeight(root) != -1; } private int getHeight (TreeNode root){ if(root == null){ return 0; } int left = getHeight(root.left); int right = getHeight(root.right); if(left == -1 || right == -1){ return -1; } if(Math.abs(left -right) > 1){ return -1; } return 1 + Math.max(left, right); } }
257. Binary Tree Paths
- 思路
- 这里递归要用前序遍历
-
java class Solution { public List binaryTreePaths(TreeNode root) { List res = new ArrayList<>(); if (root == null){ return res; } List paths = new ArrayList<>(); helper(root, paths, res); return res; } private void helper(TreeNode root, List paths, List res){ //虽然是前序遍历"中, 左, 右" 中写在最上面是为了保证叶子节点进数组path paths.add(root.val); //终止条件 if (root.left == null && root.right == null){ res.add(path2Str(paths)); return; } //前序遍历 左 if(root.left != null){ helper(root.left, paths, res); paths.remove(paths.size() -1); } //前序 右 if(root.right != null){ helper(root.right, paths, res); paths.remove(paths.size() -1); } } // helper 把 path的数组变成符合要求的字符串 private String path2Str(List path){ StringBuilder temp = new StringBuilder(); for(int i : path){ temp.append(i); temp.append("->"); } temp.deleteCharAt(temp.length() - 1); temp.deleteCharAt(temp.length() - 1); return temp.toString(); } }
- 思路
- 后序遍历数字往上堆
-
java class Solution { public int sumOfLeftLeaves(TreeNode root) { if (root == null){ return 0; } if (root.left == null && root.right == null){ return 0; } int left = sumOfLeftLeaves(root.left); //能进入到这个if判断的,root.left是叶子节点,所以上面那条left = sumOfLefLeaves(root.left) 返回肯定是0,不存在覆盖数字的问题 if(root.left != null && root.left.left == null && root.left.right == null){ left = root.left.val; } int right = sumOfLeftLeaves(root.right); int sum = left + right; return sum; } }
- 层序遍历BFS
-
java class Solution { public int sumOfLeftLeaves(TreeNode root) { int sum = 0; if (root == null){ return 0; } Queue queue = new LinkedList<>(); queue.add(root); while(!queue.isEmpty()){ int size = queue.size(); while(size > 0){ TreeNode node = queue.poll(); if(node.left != null){ queue.add(node.left); if(node.left.left == null && node.left.right == null){ sum += node.left.val; } } if(node.right != null){ queue.add(node.right); } size--; } } return sum; } }