617. Merge Two Binary Trees

1. Description

Given two binary trees and 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 them 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 new tree.

2. Note

  • The merging process must start from the root nodes of both trees.

3. Solutions

My Accepted Solution

n is the min number of nodes in i_root
Time complexity: O(n)
Space complexity: O(n)

class Solution 
{
public:
    // TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2)
    vector<double> averageOfLevels(TreeNode *i_root) 
    {
        if(!i_root) return vector<double>{};
        
        vector<double> result{(double)i_root->val};
        queue<const TreeNode *> currentLevelNodes{{i_root}};
        queue<const TreeNode *> nextLevelNodes;
        
        int lastLevelSize = 0;
        double lastLevelSum = 0;
        while(!currentLevelNodes.empty() || !nextLevelNodes.empty())
        {
            if(currentLevelNodes.empty())
            {
                swap(currentLevelNodes, nextLevelNodes); 
                
                lastLevelSize = currentLevelNodes.size();
                result.push_back(lastLevelSum / lastLevelSize);
                lastLevelSum = 0;
            }
            else
            {
                auto node = currentLevelNodes.front();
                currentLevelNodes.pop();
                
                if(node->left)
                {
                    lastLevelSum += node->left->val;
                    nextLevelNodes.push(node->left);
                }
                if(node->right)
                {
                    lastLevelSum += node->right->val;
                    nextLevelNodes.push(node->right);    
                }
            }
        }
        
        return result;
    }
};
Last updated:
Tags: Tree
comments powered by Disqus