首页 > 技术文章 > 最深叶节点的最近公共祖先

xiezi1015 2019-07-22 10:03 原文

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

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);
}
}

推荐阅读