剑指offer-day18
二叉树的深度
第一道自己写出来的树题!可以说非常具有纪念意义了,时空复杂度也不输最优解,自豪地放上自己的解。
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
|
class Solution { int depth; int max; public int maxDepth(TreeNode root) { if(root == null){ return 0; } depth = 0; max = 0; preorder(root); return max; }
public void preorder(TreeNode root){ depth++; if(root == null){ depth--; max = Math.max(max,depth); return; } preorder(root.left); preorder(root.right); depth--; } }
|
平衡二叉树
半写半抄完成的,用的是从上到下的递归,然而并不是最优解,最优解是从下到上的递归+剪枝。使用后序遍历从叶子节点往上遍历,每次遍历时看以该节点为根的子树是否是平衡二叉树,如果是则返回该子树的高度,否则返回-1,表示该树不是平衡二叉树。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public boolean isBalanced(TreeNode root) { return recur(root) != -1; }
private int recur(TreeNode root) { if (root == null) return 0; int left = recur(root.left); if(left == -1) return -1; int right = recur(root.right); if(right == -1) return -1; return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1; } }
|