Smallest Subtree with all the Deepest Nodes

Similar Problems:

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.

Note:

- The number of nodes in the tree will be between 1 and 500.
- The values of each node are unique.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.

- Solution:

// Blog link: https://code.dennyzhang.com/smallest-subtree-with-all-the-deepest-nodes // Basic Ideas: BFS // Build child to parent hashmap // Find the deepest leaves // BFS from bottom to up // When the queue has only one element, return the result // // Complexity: Time O(n), Space O(n) /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func subtreeWithAllDeepest(root *TreeNode) *TreeNode { if root == nil { return nil } if root.Left == nil && root.Right == nil { return root } // bfs: deepest leaves and hashmap for child-to-parent m := map[int]*TreeNode{} queue := []*TreeNode{root} leaves := []*TreeNode{} for len(queue) != 0 { leaves = queue l := []*TreeNode{} for _, node := range queue { if node.Left != nil { l = append(l, node.Left) m[node.Left.Val] = node } if node.Right != nil { l = append(l, node.Right) m[node.Right.Val] = node } } queue = l } // bfs: bottom up for len(leaves) > 1 { l := []*TreeNode{} m2 := map[int]bool{} for _, node := range leaves { // parent node value v := m[node.Val].Val if !m2[v] { l = append(l, m[node.Val]) m2[v] = true } } leaves = l } return leaves[0] }