[LeetCode] 617. Merge Two Binary Trees
来源:互联网 发布:最伟大的意大利人知乎 编辑:程序博客网 时间:2024/06/05 14:21
Problem :
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.
Example 1:
Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7
Note: The merging process must start from the root nodes of both trees.
解题思路:构造树的问题很容易联想到用分治法来解决,这道题的特殊之处在于,每构造一个节点需要考虑四种情况:
1. 两子树节点均为空
2. t1节点为空,t2节点不为空
3. t1节点不为空,t2节点为空
4. 两子树节点均不为空
递归简单求解:
/** * 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) { return mergeEachNode(t1, t2); } // 分四种情况合并每个树节点 TreeNode* mergeEachNode(TreeNode* t1, TreeNode* t2) { TreeNode* root = NULL; if (t1 == NULL && t2 == NULL) return NULL; if (t1 != NULL && t2 == NULL) { root = new TreeNode(t1->val); root->left = mergeEachNode(t1->left, NULL); root->right = mergeEachNode(t1->right, NULL); } if (t1 == NULL && t2 != NULL) { root = new TreeNode(t2->val); root->left = mergeEachNode(t2->left, NULL); root->right = mergeEachNode(t2->right, NULL); } if (t1 != NULL && t2 != NULL) { root = new TreeNode(t1->val + t2->val); root->left = mergeEachNode(t1->left, t2->left); root->right = mergeEachNode(t1->right, t2->right); } return root; }};
阅读全文
0 0
- [leetcode]617. Merge Two Binary Trees
- leetcode.617.Merge Two Binary Trees
- [leetcode]: 617. Merge Two Binary Trees
- [Leetcode]617. Merge Two Binary Trees
- LeetCode 617. Merge Two Binary Trees (C++)
- LeetCode 617. Merge Two Binary Trees
- [LeetCode] 617. Merge Two Binary Trees
- LeetCode 617. Merge Two Binary Trees
- 【Leetcode】617. Merge Two Binary Trees
- [LeetCode]617.Merge Two Binary Trees
- LeetCode: 617. Merge Two Binary Trees
- Leetcode 617. Merge Two Binary Trees
- [leetcode]617. Merge Two Binary Trees
- [Leetcode] 617. Merge Two Binary Trees
- [LeetCode]617. Merge Two Binary Trees
- leetcode 617. Merge Two Binary Trees
- 【LeetCode】617. Merge Two Binary Trees
- [LeetCode]617. Merge Two Binary Trees<Java>
- 记录JDBC连接sqlserver(MSSQL) 数据库
- noip防低级错误手册
- OMA DRM介绍
- USB设备开发---- usb描述符概述
- 调整数组顺序使奇数位于偶数前面
- [LeetCode] 617. Merge Two Binary Trees
- JavaScript的原型链
- java中System.getProperty()和System.setProperty()和System.getProperties()
- IMX6平台:Linux编译Kernel、Uboot等出错问题汇总
- 企业上项目管理软件到底是对还是错?
- JavaScript学习笔记_非构造函数的继承
- php日期
- S5PV210 构建最小linux系统(2)---->Uboot移植
- 易观 CTO 郭炜:易观大数据架构的变迁