104/110/111/559. Max/Min Depth of Binary/N Tree --二叉樹或者N叉樹深度
阿新 • • 發佈:2018-11-08
104. Maximum Depth of Binary Tree
求二叉樹最大深度
3 / \ 9 20 / \ 15 7
return its depth = 3.
class Solution { public int maxDepth(TreeNode root) { if(root ==null) return 0; int h_l = maxDepth(root.left)+1; int h_r = maxDepth(root.right)+1;return Math.max(h_l,h_r); } }
559. Maximum Depth of N-ary Tree
一開始寫成這樣, 結果怎麼都不對:
因為 這裡 maxDepth(child) 根本不會 hit root ==null 的情況,因為如果沒有葉子節點, children 直接為空, 不會進行遞迴。
class Solution { public int maxDepth(Node root) { if(root ==null) return 0;int max = Integer.MIN_VALUE; //不能寫成 這樣 for(Node child: root.children){ max = Math.max(max, maxDepth(child)); } return max+1; } }
為了便於理解,寫成這樣, 注意 helper裡 不需要 if(root ==null) return 0 的判斷。
class Solution { public int maxDepth(Node root) {if(root ==null) return 0; return helper(root); } int helper(Node node){ int max = 0; for(Node child: node.children){ max = Math.max(max, maxDepth(child)); } return max+1; } }
111. Minimum Depth of Binary Tree 求最小深度
一開始直接無腦寫成這樣,直接就WA掉了。
class Solution { public int minDepth(TreeNode root) { if(root ==null) return 0; return Math.min(minDepth(root.left), minDepth(root.right)) +1; } }
注意, 最小深度時,如果 某個節點沒有某個子節點 不計算在內, 例如 1: 2, null , 最小深度為2,用過用上面的演算法 返回為1了。
正確寫法:
class Solution { public int minDepth(TreeNode root) { if(root ==null) return 0; int left = minDepth(root.left); int right = minDepth(root.right); return (left==0 || right==0)? left+right+1: Math.min(left,right)+1; } }
BFS 寫法:
class Solution { public int minDepth(TreeNode root) { if(root == null) return 0; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); int level = 0; while(!queue.isEmpty()){ TreeNode node; int size = queue.size(); level++; for(int i = 0; i<size; i++){ node = queue.remove(); if(node.left==null && node.right==null) {return level;} //說明已經是最小 直接返回 if(node.left!=null) queue.add(node.left); if(node.right!=null) queue.add(node.right); } } return level; } }
110. Balanced Binary Tree
左右子樹深度差不超過1的樹稱為 平衡二叉樹,如果是空數的話也是平衡二叉樹。
演算法: DFS求左右子數深度,求解過程中判斷深度差。
演算法一: 遞迴過程中加一個flag, 只要有不滿足條件的 flag = false,但這樣的寫法需要額外定義flag, code 寫的不夠漂亮。
class Solution { public boolean isBalanced(TreeNode root) { boolean[] flag = new boolean[1]; flag[0] = true; depth(root,flag); return flag[0]; } private int depth(TreeNode root, boolean[] flag){ if(root == null) return 0; int depth_left = 1+ depth(root.left,flag); int depth_right = 1+ depth(root.right,flag); //System.out.println(depth_left+ " "+depth_right); if(Math.abs(depth_left -depth_right) >1) { flag[0] = false; return -1; } return Math.max(depth_left,depth_right); } }
改進演算法: 出現非對稱的子數就返回-1, 並且後面都返回-1.
class Solution { public boolean isBalanced(TreeNode root) { return depth(root) >= 0; } private int depth(TreeNode root){ if(root == null) return 0; int depth_left = depth(root.left); int depth_right = depth(root.right); if(Math.abs(depth_left -depth_right) >1) { return -1; } return (depth_left== -1 || depth_right == -1) ? -1: Math.max(depth_left,depth_right)+1; } }