【树】1123. 最深叶节点的最近公共祖先

题目:

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

回想一下:

叶节点 是二叉树中没有子节点的节点
树的根节点的 深度 为 0,如果某一节点的深度为 d,那它的子节点的深度就是 d+1
如果我们假定 A 是一组节点 S 的 最近公共祖先,S 中的每个节点都在以 A 为根节点的子树中,且 A 的深度达到此条件下可能的最大值。
 

示例 1:

输入:root = [1,2,3]
输出:[1,2,3]
解释:
最深的叶子是值为 2 和 3 的节点。
这些叶子的最近共同祖先是值为 1 的节点。
返回的答案为序列化的 TreeNode 对象(不是数组)"[1,2,3]" 。

 

解答:

方法一:DFS

如果当前节点的左右子树的高度相等,则当前节点就是要找的最近公共祖先。

如果左子树的高度大于右子树,则最近公共祖先在左子树。

否则,最近公共祖先在右子树。

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

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

 

posted @ 2020-10-08 19:55  3KBLACK  阅读(136)  评论(0)    收藏  举报