给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
示例 1:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3。
示例 2:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出: 5
解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null||root==p||root==q)return root;
TreeNode left=LowestCommonAncestor(root.left,p,q);
TreeNode right=LowestCommonAncestor(root.right,p,q);
if(left==null)
return right;
if(right ==null)
return left;
return root;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
Dictionary<TreeNode, TreeNode > parent = new Dictionary<TreeNode, TreeNode >();
Queue<TreeNode> contain = new Queue<TreeNode>();
contain.Enqueue(root);
parent.Add(root,null);
while (!parent .ContainsKey (p )||!parent .ContainsKey (q))
{
TreeNode temp = contain.Dequeue();
if (temp.left != null)
{
contain.Enqueue(temp.left);
parent.Add(temp.left, temp);
}
if (temp.right != null)
{
contain.Enqueue(temp.right);
parent.Add(temp.right, temp);
}
}
HashSet<TreeNode> ancestors = new HashSet<TreeNode>();
while (p != null)
{
ancestors.Add(p);
p = parent[p];
}
while (!ancestors .Contains (q))
{
q = parent[q];
}
return q;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
public TreeNode ans=null;
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
recurseTree(root,p,q);
return this. ans;
}
public bool recurseTree(TreeNode root, TreeNode p, TreeNode q)
{
if(root==null)
return false ;
int left=recurseTree(root.left,p,q)?1:0;
int right=recurseTree(root.right,p,q)?1:0;
int mid=(root==p||root==q)?1:0;
if(left+right+mid>=2)
this.ans=root;
if(left+right+mid>0)return true;
else return false;
}
}
第三种方法是答案的一种方法十分巧妙,看了半天才看懂,保存一下方便以后复习
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import javafx.util.*;
class Solution {
// Three static flags to keep track of post-order traversal.
// Both left and right traversal pending for a node.
// Indicates the nodes children are yet to be traversed.
private static int BOTH_PENDING = 2;
// Left traversal done.
private static int LEFT_DONE = 1;
// Both left and right traversal done for a node.
// Indicates the node can be popped off the stack.
private static int BOTH_DONE = 0;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
Stack<Pair<TreeNode, Integer>> stack = new Stack<Pair<TreeNode, Integer>>();
// Initialize the stack with the root node.
stack.push(new Pair<TreeNode, Integer>(root, Solution.BOTH_PENDING));
// This flag is set when either one of p or q is found.
boolean one_node_found = false;
// This is used to keep track of the LCA.
TreeNode LCA = null;
// Child node
TreeNode child_node = null;
// We do a post order traversal of the binary tree using stack
while (!stack.isEmpty()) {
Pair<TreeNode, Integer> top = stack.peek();
TreeNode parent_node = top.getKey();
int parent_state = top.getValue();
// If the parent_state is not equal to BOTH_DONE,
// this means the parent_node can't be popped off yet.
if (parent_state != Solution.BOTH_DONE)
{
// If both child traversals are pending
if (parent_state == Solution.BOTH_PENDING)
{
// Check if the current parent_node is either p or q.
if (parent_node == p || parent_node == q)
{
// If one_node_found was set already, this means we have found
// both the nodes.
if (one_node_found)
{
return LCA;
} else
{
// Otherwise, set one_node_found to True,
// to mark one of p and q is found.
one_node_found = true;
// Save the current top element of stack as the LCA.
LCA = stack.peek().getKey();
}
}
// If both pending, traverse the left child first
child_node = parent_node.left;
} else
{
// traverse right child
child_node = parent_node.right;
}
// Update the node state at the top of the stack
// Since we have visited one more child.
stack.pop();
stack.push(new Pair<TreeNode, Integer>(parent_node, parent_state - 1));
// Add the child node to the stack for traversal.
if (child_node != null) {
stack.push(new Pair<TreeNode, Integer>(child_node, Solution.BOTH_PENDING));
}
}
else {
// If the parent_state of the node is both done,
// the top node could be popped off the stack.
// Update the LCA node to be the next top node.
if (LCA == stack.pop().getKey() && one_node_found) {
LCA = stack.peek().getKey();
}
}
}
return null;
}
}