給你一個有根節點的二叉樹,找到它最深的葉節點的最近公共祖先。
回想一下:
葉節點 是二叉樹中沒有子節點的節點
樹的根節點的 深度 為 0,如果某一節點的深度為 d,那它的子節點的深度就是 d+1
如果我們假定 A 是一組節點 S 的 最近公共祖先,S 中的每個節點都在以 A 為根節點的子樹中,且 A 的深度達到此條件下可能的最大值。
示例 1:
輸入:root = [1,2,3]
輸出:[1,2,3]
解釋:
最深的葉子是值為 2 和 3 的節點。
這些葉子的最近共同祖先是值為 1 的節點。
返回的答案為序列化的 TreeNode 對象(不是數組)"[1,2,3]" 。
代碼
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {int maxLen=Integer.MIN_VALUE;TreeNode maxRoot;public TreeNode lcaDeepestLeaves(TreeNode root) {po(root,0);return maxRoot;}public int po(TreeNode root,int level) {if(root==null) return level;//返回深度int l=po(root.left,level+1);int r=po(root.right,level+1);if(l==r&&l>=maxLen) {//如果左右子樹都存在相等的最深葉子節點maxLen=l;maxRoot=root;}return Math.max(l,r);//返回最深葉子節點的高度}
}