二叉樹最近公共祖先
阿新 • • 發佈:2017-06-24
ret highlight 筆試 代碼 light brush 二叉 init blog
給定一棵二叉樹,找到兩個節點的最近公共父節點(LCA)。最近公共祖先是兩個節點的公共的祖先節點且具有最大深度。
樣例:
對於下面這棵二叉樹
4
/ \
3 7
/ \
5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
這道題筆者最近在筆試中也遇到過,相對比較簡單,代碼如下:
/** * 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 and B: two nodes in a Binary. * @return: Return the least common ancestor(LCA) of the two nodes. */ TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *A, TreeNode *B) { if (root == NULL || A == root || B == root) return root; TreeNode *left = lowestCommonAncestor(root->left, A, B); TreeNode *right = lowestCommonAncestor(root->right, A, B); if (left != NULL && right != NULL) return root; return left ? left : right; } };
二叉樹最近公共祖先