最深叶节点的最近公共祖先

给你一个有根节点的二叉树,找到它最深的叶节点的最近公共祖先。

code:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lcaDeepestLeaves(TreeNode root) {
if(root == null)
return null;
int left = depth(root.left);
int right = depth(root.right);
if(left == right)
return root;
else if(left > right)
return lcaDeepestLeaves(root.left);
else
return lcaDeepestLeaves(root.right);

}
int depth(TreeNode root)
{
if(root == null)
return 0;
int left = depth(root.left);
int right = depth(root.right);
return 1 + Math.max(left, right);
}
}

猜你喜欢

转载自www.cnblogs.com/xiezi1015/p/11224189.html