Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.
Return the merged tree.
Note: The merging process must start from the root nodes of both trees.
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Example 1:
Input: root = [1,2,3,4,5,6,7]
Output: [1,#,2,3,#,4,5,6,7,#]
Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Example 2:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 2^12 - 1].
-1000 <= Node.val <= 1000
Follow-up:
You may only use constant extra space.
The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
Solution
Approach #0: BFS
/** * Definition for a Node. * type Node struct { * Val int * Left *Node * Right *Node * Next *Node * } */funcconnect(root *Node) *Node {if root ==nil {return root } queue := []*Node{root}forlen(queue) >0 { size :=len(queue)for i :=0; i < size; i++ {if i+1< size { queue[i].Next = queue[i+1] }if queue[i].Left !=nil { queue =append(queue, queue[i].Left, queue[i].Right) } } queue = queue[size:] }return root}
Approach #1: DFS (Iterative)
/** * Definition for a Node. * type Node struct { * Val int * Left *Node * Right *Node * Next *Node * } */funcconnect(root *Node) *Node {if root ==nil {return root }for l := root; l.Left !=nil; l = l.Left {for node := l; node !=nil; node = node.Next { node.Left.Next = node.Rightif node.Next !=nil { node.Right.Next = node.Next.Left } } }return root}
Approach #2: DFS (Recursive)
/** * Definition for a Node. * type Node struct { * Val int * Left *Node * Right *Node * Next *Node * } */funcconnect(root *Node) *Node {if root ==nil {return root }dfs(root, nil)return root}funcdfs(left, next *Node) {if left ==nil {return } left.Next = nextdfs(left.Left, left.Right)if left.Next ==nil {dfs(left.Right, nil) } else {dfs(left.Right, left.Next.Left) }}