Home > Back-end >  Recent common ancestor of binary tree
Recent common ancestor of binary tree

Time:12-05

Given a binary tree, found the tree in the recent common ancestor of two specified node,

Baidu encyclopedia in recent common ancestor is defined as: "for a two nodes with root tree T p, q, recent common ancestor is expressed as a node x, meet x is p, q ancestors and the depth of the x as large as possible (a node) may also be its own ancestors,"

For example, a given binary tree as follows: root=[3,5,1,6,2,0,8, null, null, 7, 4]





Example 1:

Input: root=[3,5,1,6,2,0,8, null, null, 7, 4], p=5, q=1
Output: 3
Explanation: the node 5 and 1 recent common ancestor node 3,
Example 2:

Input: root=[3,5,1,6,2,0,8, null, null, 7, 4], p=5, q=4
Output: 5
Explanation: node 5 nodes and four recent common ancestor is 5, because recent common ancestor nodes according to the definition for the node itself,


Description:

All the values of the nodes is unique,
P and q for different nodes and all exists in a given binary tree,

Non-recursive solution:
Struct TreeNode {
Int val.
Struct TreeNode * left;
Struct TreeNode * right;
};

Struct TreeNode * lowestCommonAncestor (struct root TreeNode * and struct TreeNode * p, struct TreeNode * q) {
Struct TreeNode * stack [20000];
Int top=0, ancestorDepth=1;
Struct cur=root TreeNode * and * ancestor=NULL;
While ((cur | | top> 0) & amp; & Ancestor!={
root)While (cur) {
Stack [top++]=cur;
Cur=cur - & gt; The left;
}
Cur=stack [-- top];
If (top & lt; AncestorDepth) {
Ancestor=cur;
AncestorDepth=top;
}
If (cur==p | | cur==q) {
If (ancestor) break;
Ancestor=cur;
AncestorDepth=top;
}
Cur=cur - & gt; Right;
}
Return ancestor;
}
didn't completely understand the thinking of the code, please bosses detailed analysis, I am a kindergarten children
  • Related