LeetCode 617. Merge Two Binary Trees

LeetCode 617. Merge Two Binary Trees

题目大意:

根据已给的二叉树,将相对应位置的值相加,获得合并后的二叉树。(空值相当于0)

-Example:

Input:
    Tree 1                     Tree 2                  
              1                         2                             
             / \                       / \                            
            3   2                     1   3                        
           /                           \   \                      
          5                             4   7    
Output:
    Merged tree:
         3
        / \
       4   5
      / \   \ 
     5   4   7

[3,4,5,5,4,null,7]

已给代码格式如下

/**
  Definition for a binary tree node.
  struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  };
 */
class Solution {
public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
    }
 }

思路分析

根据题中所给例子可知:先序遍历两个二叉树,将相对应位置的值相加即可
根据该思路可得初始代码如下:

TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        TreeNode* t3 = new TreeNode(t1->val+t2->val);
        t3->left = mergeTrees(t1->left,t2->left);
        t3->right = mergeTrees(t1->right, t2->right);
        return t3;
    }

但是运行可知,该代码无法处理二叉树为空的情况。根据题意又可知:t1为空树时,返回结果为t2的值,t2为空树时,返回结果为t1的值
所以改进后的代码如下:

TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        if(!t1)
            return t2;
        if(!t2)
            return t1;
        TreeNode* t3 = new TreeNode(t1->val+t2->val);
        t3->left = mergeTrees(t1->left,t2->left);
        t3->right = mergeTrees(t1->right, t2->right);
        return t3;
    }

分析总结

该代码与LeetCode相似,都是由二叉树的先序遍历改进而来,但是对于二叉树为空时的处理不同。如果不对空二叉树进行处理,运行后会显示错误:
Run Code Status: Runtime Error
Line 14: member access within null pointer of type ‘struct TreeNode’

你可能感兴趣的:(LeetCode)