給定一棵二叉樹,找到兩個節點的最近公共父節點(LCA)。
最近公共祖先是兩個節點的公共的祖先節點且具備最大深度。
注意事項:
假設給出的兩個節點都在樹中存在。node
思路:
查找兩個node的最先的公共祖先,分三種狀況:this
- 若是兩個node在root的兩邊,那麼最先的公共祖先就是root。
- 若是兩個node在root的左邊,那麼把root的左子樹做爲root,再遞歸。
- 若是兩個node在root的右邊,那麼把root的右子樹做爲root,再遞歸。
自底向上的遍歷二叉樹(深度優先遍歷),一旦找到了兩個節點其中的一個,就將這個幾點返回給上一層,上一層節點經過判斷其左右子樹中是否剛好包含n1和n2兩個節點,若是是這樣的話,對應的上一層節點確定是所求的LCA;若果不是的話,將包括兩個節點中任意一個的較低的節點返回給上一層,不然返回NULL。spa
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /* * @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. */ TreeNode * lowestCommonAncestor(TreeNode * root, TreeNode * A, TreeNode * B) { // write your code here //若是當前節點爲空,或者與目標節點中的一個相同,則返回該節點 if(root == NULL) return NULL; if(root==A || root==B) return root; //遞歸尋找A B在左右子樹的位置 TreeNode* left = lowestCommonAncestor(root->left,A,B); TreeNode* right = lowestCommonAncestor(root->right,A,B); //若是A B分別位於root的兩側,則root是他們的LCA,不然是左子樹或者右子樹 if(left&&right) return root; return left?left:right; } };