Most recent common ancestor of leaf nodes

Give you a root node of a binary tree, find the nearest common ancestor of the deepest leaf node.

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

Guess you like

Origin www.cnblogs.com/xiezi1015/p/11224189.html