FB面經 Prepare: LCA of Deepest Nodes in Binary Tree

 

給一個 二叉樹 , 求最深節點的最小公共父節點
     1
  2   3
     5  6    return 3.

       1  
    2   3
4      5 6   retrun 1. 
先用 recursive  , 很快寫出來了, 要求用 iterative 。 時間不夠了。。。

Recursion: 返回的時候返回lca和depth每一個node若是有大於一個子節點的depth相同就返回這個node,若是有一個子節點depth更深就返回個子節點lca,這個o(n)就能夠了node

Iteration: tree的recursion換成iteration處理,通常用stack都能解決吧(至關於手動用stack模擬recursion)。感受這題能夠是一個樣的作法,換成post order訪問,這樣處理每一個node的時候,左右孩子的信息都有了,並且最後一個處理的node必定是tree rootpost

個人想法是要用hashMap<TreeNode, Info>spa

class Info{code

  int height;blog

  TreeNode LCA;hash

}it

 1 package fbOnsite;
 2 
 3 
 4 public class LCA2 {
 5     private class ReturnVal {
 6         public int depth;   //The depth of the deepest leaves on the current subtree
 7         public TreeNode lca;//The lca of the deepest leaves on the current subtree
 8 
 9         public ReturnVal(int d, TreeNode n) {
10             depth = d;
11             lca = n;
12         }
13     }
14 
15     public TreeNode LowestCommonAncestorOfDeepestLeaves(TreeNode root) {
16         ReturnVal res = find(root);
17         return res.lca;
18     }
19 
20     private ReturnVal find(TreeNode root) {
21         if(root == null) {
22             return new ReturnVal(0, null);
23         } else {
24             ReturnVal lRes = find(root.left);
25             ReturnVal rRes = find(root.right);
26 
27             if(lRes.depth == rRes.depth) {
28                 return new ReturnVal(lRes.depth+1, root);
29             } else {
30                 return new ReturnVal(Math.max(rRes.depth, lRes.depth)+1, rRes.depth>lRes.depth?rRes.lca:lRes.lca);
31             }
32         }
33     }
34 
35 
36 
37 
38 /**
39  * @param args
40  */
41     public static void main(String[] args) {
42         // TODO Auto-generated method stub
43         TreeNode t1 = new TreeNode(1);
44         TreeNode t2 = new TreeNode(2);
45         TreeNode t3 = new TreeNode(3);
46         TreeNode t4 = new TreeNode(4);
47         TreeNode t5 = new TreeNode(5);
48         TreeNode t6 = new TreeNode(6);
49         TreeNode t7 = new TreeNode(7);
50         t1.left = t2;
51         t1.right = t3;
52         t2.left = t4;
53         //t3.left = t5;
54         //t3.right = t6;
55         t2.right = t7;
56         LCA sol = new LCA();
57         TreeNode res = sol.LowestCommonAncestorOfDeepestLeaves(t1);
58         System.out.println(res.val);
59     }
60 }
相關文章
相關標籤/搜索