1. 程式人生 > >lintcode88- Lowest Common Ancestor I- medium

lintcode88- Lowest Common Ancestor I- medium

arc earch mon alert blog roo nbsp logs med

Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.

The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.

Notice

Assume two nodes are exist in tree.

Example

For the following binary tree:

  4
 / 3   7
   /   5   6

LCA(3, 5) = 4

LCA(5, 6) = 7

LCA(6, 7) = 7

分治法來遞歸做。

定義好四種返回值。如果root看到A,就返回A;如果root看到B,就返回B;如果root看到null或者過完整個函數發現什麽都沒找到,就返回null;如果中間求解到了答案,就返回答案LCA。

根據定義,在分治的時候看左右兩邊。

1.如果左右都不為空,那肯定是A,B一左一右落在兩邊了。那這時候root絕對就是答案,返root。

2.如果左不空右空,那肯定是右邊空空蕩蕩什麽都沒有,左邊要麽是AB都在現在拿到答案了,要麽左邊把A/B返上來證明自己碰到一個了,總而言之都返left。

3.如果左空右不空,同理返right。

4.如果左右都空,肯定是下面AB都沒碰到過,更沒碰到過答案了,返回null來說明自己什麽都沒碰到。

做好後細致分析一下,

1.如果AB在某個地方岔開來兩邊,按這種做法遞歸到分叉點肯定能識別到左右非null,從而返回這個root點,之後一路向上都是把這個答案送上去的(因為另一側沒AB了會返null)。穩。

2.如果A是B的父親,在到A作為root傳入的那一層,一開始就把A返回去了,而且A右邊的樹不會碰到AB,傳null一路保A上去。穩。

3.如果B是A的父親,同理,穩。

所以這個遞歸的定義和實現是可行的。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 
*/ public class Solution { /* * @param root: The root of the binary search tree. * @param A: A TreeNode in a Binary. * @param B: A TreeNode in a Binary. * @return: Return the least common ancestor(LCA) of the two nodes. */ 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); TreeNode right = lowestCommonAncestor(root.right, A, B); if (left != null && right != null) { return root; } if (left != null) { return left; } if (right != null) { return right; } return null; } }

lintcode88- Lowest Common Ancestor I- medium