二叉樹---最近公共父節點(LCA)
阿新 • • 發佈:2017-07-15
點子 clas urn com 祖先 ces 代碼 col 深度
題目:
給定一棵二叉樹,找到兩個節點的最近公共父節點(LCA)。
最近公共祖先是兩個節點的公共的祖先節點且具有最大深度。
4
/ 3 7
/ 5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
Java代碼:
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) { // write your code here if(root == null||root == A||root == B){return root; } //分而 TreeNode left = lowestCommonAncestor(root.left, A, B);//這裏主要用來找根節點子樹是否有A或B節點;因為有可能A或B在一側或者各自在一側,這是都有可能的。 TreeNode right = lowestCommonAncestor(root.right, A, B); //治之 if(left!=null&&right!=null){ //如果這個節點不是A或B的話就返回該節點,然後繼續往下搜索 returnroot; } if(left!=null){ return left; } if(right != null){ return right; } return null; }
二叉樹---最近公共父節點(LCA)