Leetcode - Integer to English Words
Leetcode - Uncrossed Lines

Leetcode - Smallest Subtree with all the Deepest Nodes

violet posted @ May 25, 2020 01:44:40 AM in 算法 with tags Algorithm Golang DFS tree , 234 阅读

https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/

Given a binary tree rooted at root, the depth of each node is the shortest distance to the root.

A node is deepest if it has the largest depth possible among any node in the entire tree.

The subtree of a node is that node, plus the set of all descendants of that node.

Return the node with the largest depth such that it contains all the deepest nodes in its subtree.

 

Example 1:

Input: [3,5,1,6,2,0,8,null,null,7,4]
Output: [2,7,4]
Explanation:

We return the node with value 2, colored in yellow in the diagram. The nodes colored in blue are the deepest nodes of the tree. The input "[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]" is a serialization of the given tree. The output "[2, 7, 4]" is a serialization of the subtree rooted at the node with value 2. Both the input and output have TreeNode type.

 

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func subtreeWithAllDeepest(root *TreeNode) *TreeNode {
    var result *TreeNode
    deepest := 0
    dfs(root, &result, &deepest, 0)
    return result
}

func dfs(root *TreeNode, result **TreeNode, deepest *int, level int) int {
    if root == nil {
        return level
    }
    left := dfs(root.Left, result, deepest, level+1)
    right := dfs(root.Right, result, deepest, level+1)
    
    curr := max(left, right)
    *deepest = max(*deepest, curr)
    
    if left == *deepest && right == *deepest {
        *result = root
    }
    return curr
}

func max(a, b int) int{
    if a > b {
        return a
    }
    return b
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter