【二叉树】617. Merge Two Binary Trees
来源:互联网 发布:专业性书籍阅读软件 编辑:程序博客网 时间:2024/06/08 18:36
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.
解答:
/** * 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) { if(!t1)return t2; if(!t2)return t1; TreeNode* root=new TreeNode(t1->val+t2->val); root->left=mergeTrees(t1->left,t2->left); root->right=mergeTrees(t1->right,t2->right); return root; }};
阅读全文
0 0
- 【二叉树】617. Merge Two Binary Trees
- 617. Merge Two Binary Trees(二叉树的合并)
- 617. Merge Two Binary Trees 二叉树合并
- 617. Merge Two Binary Trees(合并二叉树)
- 617. Merge Two Binary Trees
- 617. Merge Two Binary Trees
- 617. Merge Two Binary Trees
- 617. Merge Two Binary Trees
- 617. Merge Two Binary Trees
- 617. Merge Two Binary Trees
- 617. Merge Two Binary Trees
- 617. Merge Two Binary Trees
- 617. Merge Two Binary Trees
- 617. Merge Two Binary Trees
- 617. Merge Two Binary Trees
- 617. Merge Two Binary Trees
- 617. Merge Two Binary Trees
- 617. Merge Two Binary Trees
- python学习(1)
- 错排公式详解
- 我们有自己的团队了!!!!
- sql 多个排序字段解释
- python practice 02
- 【二叉树】617. Merge Two Binary Trees
- Android 自定义View之八等份仪表盘
- 数值类型、字符串
- oracle数据库远程连接方法
- 有个女生问我“做一个APP的大致流程是什么”,我打了不少字,不舍得删,就放这里吧
- 网页编程--HTML
- sql server 2014 各版本区别
- Mac-CentOS部署JavaWeb工程
- spring表达式