[LeetCode]236 二叉樹的最近公共父親節點
阿新 • • 發佈:2018-12-31
Lowest Common Ancestor of a Binary Tree(二叉樹的最近公共父親節點)
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
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).”
For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
給定一個二叉樹和所要查詢的兩個節點,找到兩個節點的最近公共父親節點(LCA)。比如,節點5和1的LCA是3,節點5和4的LCA是5。
解題思路
本題與LeetCode 235的區別就是由二叉查詢樹變為了二叉樹,即資料從有序變為了無序,那麼就不能通過root的值和兩個節點的值的大小關係來劃分查詢區域。在題235的程式碼基礎做了些許變動,同樣使用遞迴搜尋的方法,當root非空時,對root->left和root->right分別進行搜尋。若搜尋結果均非空,說明兩個節點分別位於左右子樹之中,LCA則為root;若只有一個結果為空,則LCA是另一個非空的節點;若結果均空,則返回NULL。
c++程式碼如下:
/**
* 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) {
if (!root || root == p || root == q)
return root;
TreeNode* left = lowestCommonAncestor(root->left,p,q);
TreeNode* right = lowestCommonAncestor(root->right,p,q);
if (left && right)
return root;
if (!left)
return right;
if (!right)
return left;
}
};