-
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
-
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
题解
- dfs返回一个值
- 如果左孩子是p(或q),返回p(或q),右孩子同理,否则返回null
- 每次判断root两个孩子的返回值,如果都返回了,就返回root,如果两个中有非null的就返回非null的
code
#include <stdio.h>
#include <algorithm>
#include<vector>
#include<queue>
#include<iostream>
using namespace std;
//Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//使用数组建立二叉树
TreeNode *CreateBiTree(vector<int> &a, int n, int start)//*a为data,n为数组长度,start为根节点
{
if (a[start] == -1)return nullptr;//当根节点为空,即空树
TreeNode* root = new TreeNode(a[start]);//新建一个根结点
//给根结点root的成员变量data,lchild,rchild赋初值
root->left = nullptr;
root->right = nullptr;
int lnode = 2 * start + 1;//用根节点确定左节点的位置
int rnode = 2 * start + 2;//用根节点确定右节点的位置
if (lnode > n - 1) root->left = nullptr;//超出范围为孔
else root->left = CreateBiTree(a, n, lnode);//lnode替换start,为左子树的根节点
if (rnode > n - 1) root->right = nullptr;
else root->right = CreateBiTree(a, n, rnode);//rnode替换start,为右子树的根节点
return root;
}
// void out_tree(TreeNode *head){
// if(head!= nullptr){
// cout<< head->val;
// out_tree(head->left);
// out_tree(head->right);
// }
// }
TreeNode* get_location_tree(TreeNode *head,int sval){//get location 有时不起作用
if(head!= nullptr){
if(head->val == sval){
cout<<"<--"<<sval <<endl;
return head;
}else{
cout<<"-->"<<head->val<<endl;
}
get_location_tree(head->left,sval);
get_location_tree(head->right,sval);
}
//return nullptr;
}
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) return right;
if(right == nullptr) return left;
return root;
}//作者:jyd链接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/solution/236-er-cha-shu-de-zui-jin-gong-gong-zu-xian-hou-xu/
};
int main()
{
Solution *myslo = new Solution();
vector<int> v1 = {3,5,1,6,2,0,8,-1,-1,7,4};
TreeNode *tree = CreateBiTree(v1,v1.size(),0);
TreeNode *p= nullptr;
p= get_location_tree(tree,3);
TreeNode *q= nullptr;
q= get_location_tree(tree,1);
cout<<"---"<<p<<"---"<<q<<endl;
TreeNode *res = myslo->lowestCommonAncestor(tree,p,q);
cout<<"res_output"<<endl;
cout<< res->val;
// out_tree(tree);
delete myslo;
return 0;
}