【Lintcode】1129. Smallest Subtree with All the Deepest Nodes

题目地址:

https://www.lintcode.com/problem/1129/

给定一棵二叉树,求其一棵子树,该子树包含了所有该二叉树的最深的节点。返回其根。

思路是DFS。先递归求解左右子树,返回左右子树的包含该子树的最深节点的树根,以及左右子树各自的深度,如果两个都是null,则说明当前是叶子,则返回当前节点及其深度;如果一个是null,则返回另一个;如果都不是null,则看深度,如果两者不一样深,则返回更深的那个;如果一样深,则说明当前树根是含所有最深节点的子树根,则返回当前树根及当前子树最深深度。代码如下:

public class Solution {
    
    class Pair {
        TreeNode node;
        int depth;
    
        public Pair(TreeNode node, int depth) {
            this.node = node;
            this.depth = depth;
        }
    }
    
    /**
     * @param root: a binary tree.
     * @return: return the minimun subtree contains all the key nodes.
     */
    public TreeNode subtreeWithAllKeyNodes(TreeNode root) {
        // write your code here.
        return dfs(root, 0).node;
    }
    
    private Pair dfs(TreeNode cur, int depth) {
        if (cur == null) {
            return null;
        }
    
        Pair left = dfs(cur.left, depth + 1), right = dfs(cur.right, depth + 1);
        if (left == null && right == null) {
            return new Pair(cur, depth);
        } else if (left == null) {
            return right;
        } else if (right == null) {
            return left;
        } else {
            if (left.depth > right.depth) {
                return left;
            } else if (left.depth < right.depth) {
                return right;
            } else {
                left.node = cur;
                return left;
            }
        }
    }
}

class TreeNode {
    int val;
    TreeNode left, right;
    
    public TreeNode(int val) {
        this.val = val;
    }
}

时空复杂度 O ( n ) O(n) O(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值