二叉树的最近公共祖先

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点p、q,最近公共祖先表示为一个节点x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

提示:

  • 树中节点数目在范围[2, 10^5]内。
  • -10^9 <= Node.val <= 10^9
  • 所有Node.val互不相同。
  • p != q
  • p和q均存在于给定的二叉树中。

236.二叉树的最近公共祖先

递归!

后序遍历,从下往上递归。

递归出口:当前结点为空或为目标节点,则返回该结点。

结点操作:

  • 如果左子树和右子树递归结果都是空指针,说明该节点下无目标结点,返回空指针。
  • 如果左子树和右子树递归结果都不为空指针,说明该根结点为所求LCA(因为是从下往上找的嘛。
  • 如果左子树和右子树中有一个是空结点,说明目标节点存在于某一个子树中,返回非空的子树。

就是个递归啦!想到就很简单!上代码!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* 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 == nullptr || root == p || root == q){
return root;
}
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(left == nullptr && right == nullptr){
return nullptr;
}else if(left != nullptr && right != nullptr){
return root;
}else{
return left == nullptr ? right : left;
}
}
};
Contents
|