【树】235. 二叉搜索树的最近公共祖先

题目:

解决:

方法一:递归

思路:

节点 p,q 的最近公共祖先(LCA)是距离这两个节点最近的公共祖先节点。在这里 最近 考虑的是节点的深度。下面这张图能帮助你更好的理解 最近 这个词的含义。

笔记:p 和 q其中的一个在 LCA 节点的左子树上,另一个在 LCA 节点的右子树上。

也有可能是下面这种情况:

算法:

1)从根节点开始遍历树;

2)如果节点p和节点q都在右子树上,那么以右孩子为根节点继续1的操作;

3)如果节点p和节点q都在左子树上,那么以左孩子为根节点继续1的操作;

4)如果条件2和条件3都不成立,这就意味着我们已经找到了节点p和节点q的LCA了;

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 
13     {
14         // value of current node or parent node.
15         int parentVal = root->val;
16         
17         // value of p
18         int pval = p->val;
19         // value of q
20         int qval = q->val;
21 
22         if (pval > parentVal && qval > parentVal)
23         {
24             // If both p and q are greater than parent
25             return lowestCommonAncestor(root->right, p, q);
26         }
27         else if (pval < parentVal && qval < parentVal)
28         {
29             // If both p and q are lesser than parent
30             return lowestCommonAncestor(root->left, p ,q);
31         }
32         else
33         {
34             // We have found the split point, i.e. the LCA node.
35             return root;
36         }
37     }
38 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12818345.html