LeetCode 110. 平衡二叉树
思路并不复杂,如果当前节点是平衡的,那么判断子节点是否平衡
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Solution { public boolean isBalanced (TreeNode root) { if (root == null ) { return true ; } if (Math.abs(getHeight(root.left) - getHeight(root.right)) <= 1 ) { return isBalanced(root.left) && isBalanced(root.right); }else { return false ; } } private int getHeight (TreeNode root) { if (root == null ) { return -1 ; } return Math.max(getHeight(root.left), getHeight(root.right)) + 1 ; } }
LeetCode 257.二叉树的所有路径
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 class Solution { public List<String> binaryTreePaths (TreeNode root) { List<String> ans = new LinkedList (); if (root != null ) { traversal(root, new LinkedList <Integer>(), ans); } return ans; } private void traversal (TreeNode node, List<Integer> path, List<String> ans) { path.add(node.val); if (node.left == null && node.right == null ) { StringBuilder sb = new StringBuilder (); for (int i = 0 ; i < path.size() - 1 ; i++) { sb.append(String.valueOf(path.get(i))); sb.append("->" ); } sb.append(path.get(path.size() - 1 )); ans.add(new String (sb)); return ; } if (node.left != null ) { traversal(node.left, path, ans); path.remove(path.size() - 1 ); } if (node.right != null ) { traversal(node.right, path, ans); path.remove(path.size() - 1 ); } } }
LeetCode 404.左叶子之和
递归的核心步骤,确定递归传入参数,递归出口,单层处理逻辑,over.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 class Solution { public int sumOfLeftLeaves (TreeNode root) { if (root == null ) return 0 ; if (root.left == null && root.right == null ) return 0 ; int leftValue = 0 ; if (root.left != null && root.left.left == null && root.left.right == null ) { leftValue = root.left.val; }else { leftValue = sumOfLeftLeaves (root.left); } int rightValue = sumOfLeftLeaves(root.right); return leftValue + rightValue; } }