链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-deepest-leaves/
每当到达一个节点时,计算其左右子树的深度。若相等则说明其左右子树中均存在最深叶节点,则最近公共祖先即为此节点;若不等则可直接进入较深子树。
java代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int depth = 0;
public TreeNode lcaDeepestLeaves(TreeNode root) {
if(root==null)
return null;
int leftd = depth(root.left);
int rightd = depth(root.right);
if(leftd>rightd)
return lcaDeepestLeaves(root.left);
else if(leftd == rightd)
return root;
else
return lcaDeepestLeaves(root.right);
}
private int depth(TreeNode root)
{
if(root==null)
return 0;
int leftd = depth(root.left);
int rightd = depth(root.right);
return Math.max(leftd,rightd)+1;
}
}
本文介绍了一种算法,用于解决二叉树中最深叶节点的最近公共祖先问题。通过计算节点左右子树的深度,当左右子树深度相等时,该节点即为所求的最近公共祖先。
291

被折叠的 条评论
为什么被折叠?



