题目
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 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。因为根据定义最近公共祖先节点可以为节点本身。
算法实现
//递归法
private TreeNode ans;
public Solution()
{
// 储存最近公共祖先
this.ans = null;
}
private bool recurseTree(TreeNode currentNode, TreeNode p, TreeNode q)
{
//如果到达枝节末端,返回 false
if (currentNode == null)
{
return false;
}
// 左边递归. 如果左边递归为true, 设置 left = 1 否则 0
int left = this.recurseTree(currentNode.left, p, q) ? 1 : 0;
// 右边递归
int right = this.recurseTree(currentNode.right, p, q) ? 1 : 0;
// 如果当前的 node 是 q 或 p 其中一个
int mid = (currentNode == p || currentNode == q) ? 1 : 0;
// 如果任意两个标志是 true
if (mid + left + right >= 2)
{
this.ans = currentNode;
}
// 如果三个表之中中任意一个是 true 则返回 true
return (mid + left + right > 0);
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
// 研究整个树
this.recurseTree(root, p, q);
return this.ans;
}
执行结果
执行结果 : 通过
执行用时 : 112 ms, 在所有 C# 提交中击败了100.00%的用户
内存消耗 : 27.7 MB, 在所有 C# 提交中击败了20.00%的用户
小的总结
说实话这涉及到二叉树的题,我都有点无从下手,有想法,但不知道该如何实现,所以直接借助了官方的题解,并将之移植并翻译到C#,这次稍微有些感觉,下次选几道关于二叉树的简单题,有针对性的练习肯能会加深对二叉树的理解和针对其的编程方法的掌握。
public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)//使用父指针迭代
{
// 树的栈
Stack<TreeNode> stack = new Stack<TreeNode>();
// 父指针的哈希表
Dictionary<TreeNode, TreeNode> parent = new Dictionary<TreeNode, TreeNode>();
parent.Add(root, null);
stack.Push(root);
// 重复执行直到我们找到p和q
while (!parent.ContainsKey(p) || !parent.ContainsKey(q))
{
TreeNode node = stack.Pop();
// 当我们遍历整个树的时候, 一直储存父指针
if (node.left != null)
{
parent.Add(node.left, node);
stack.Push(node.left);
}
if (node.right != null)
{
parent.Add(node.right, node);
stack.Push(node.right);
}
}
// p祖先的哈希表
HashSet<TreeNode> ancestors = new HashSet<TreeNode>();
//储存所有的p的祖先用父指针
while (p != null)
{
ancestors.Add(p);
p = parent[p];
}
// 第一个q的祖先出现在p祖先集合里,就是他们的最近公共祖先
while (!ancestors.Contains(q))
q = parent[q];
return q;
}