public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { //發現目標節點則通過返回值標記該子樹發現了某個目標結點 if(root == null || root == p || root == q) return root; //查看左子樹中是否有目標結點,沒有為null TreeNode left = lowestCommonAncestor(root.left, p, q); //查看右子樹是否有目標節點,沒有為null TreeNode right = lowestCommonAncestor(root.right, p, q); //都不為空,說明做右子樹都有目標結點,則公共祖先就是本身 if(left!=null&&right!=null) return root; //如果發現了目標節點,則繼續向上標記為該目標節點 return left == null ? right : left; } }
思路:從根節點開始遍歷,如果node1和node2中的任一個和root匹配,那么root就是最低公共祖先。 如果都不匹配,則分別遞歸左、右子樹,如果有一個 節點出現在左子樹,並且另一個節點出現在右子樹,則root就是最低公共祖先. 如果兩個節點都出現在左子樹,則說明最低公共祖先在左子樹中,否則在右子樹。
感覺很奇妙。引申的問題
如果給定的不是二叉樹,而是二叉搜索樹呢?會比較簡單一點,如果是帶有指向父節點的指針的樹,可以轉化為兩個鏈表求交匯點的問題。
235. Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
For example, the lowest common ancestor (LCA) of nodes 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 2
, since a node can be a descendant of itself according to the LCA definition.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { while((root -> val - p -> val)*(root -> val - q -> val) > 0 ){ root = root -> val > p -> val ? root -> left : root -> right; } return root; } };