1123. 最深叶节点的最近公共祖先
给你一个有根节点的二叉树,找到它最深的叶节点的最近公共祖先。
回想一下:
- 叶节点 是二叉树中没有子节点的节点
- 树的根节点的 深度 为 0,如果某一节点的深度为 d,那它的子节点的深度就是 d+1
- 如果我们假定 A 是一组节点 S 的 最近公共祖先,S 中的每个节点都在以 A 为根节点的子树中,且 A 的深度达到此条件下可能的最大值。
示例 1:
输入:root = [1,2,3]
输出:[1,2,3]
示例 2:
输入:root = [1,2,3,4]
输出:[4]
示例 3:
输入:root = [1,2,3,4,5]
输出:[2,4,5]
思路
思路:最深叶子节点的公共祖先的左右子树高度相同,也就是最深叶子节点的深度一定相同。
如果左右子树不等高,高度小的那个子树节点的叶子节点的深度肯定不是最深的(因为比高度大的子树深度小)。
所以,最深叶子节点肯定在深度较大的子树当中,采用深度优先搜索,每次只要继续往深度更大的子树进行递归即可。
如果左右子树深度相同,表示获取到了最深叶子节点的最近公共祖先
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution
{
int maxDepth = Integer.MIN_VALUE;
Queue queue = new LinkedList();
TreeNode node = null;
int getDepth(TreeNode root)
{
if(root ==null)
return 0;
int leftDepth = getDepth(root.left);
int rightDepth = getDepth(root.right);
return leftDepth>rightDepth?leftDepth+1:rightDepth+1;
}
public TreeNode bianli(TreeNode root,int depth)
{
if(root == null)
return null;
if(getDepth(root.left) == getDepth(root.right))
{
return root;
}
else if(getDepth(root.left) > getDepth(root.right))
{
return bianli(root.left,depth+1);
}
else
return bianli(root.right,depth+1);
}
public TreeNode lcaDeepestLeaves(TreeNode root)
{
if(root.left == null && root.right == null)
return root;
return bianli(root,0);
}
}
他人解法
class Solution {
private TreeNode node;
private int maxDepth;
public TreeNode lcaDeepestLeaves(TreeNode root) {
if (root == null) {
return null;
}
dfs(root, 0);
return node;
}
private int dfs(TreeNode root, int depth) {
if (root == null) {
return depth;
}
depth++;
int left = dfs(root.left, depth), right = dfs(root.right, depth);
depth = Math.max(left, right);
if (left == right && depth >= maxDepth) {
node = root;
maxDepth = depth;
}
return depth;
}
}