LeetCode二叉树合并
来源:互联网 发布:淘宝做工瑕疵运费 编辑:程序博客网 时间:2024/06/04 00:42
先上题:
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.
可以分为两种思路:
一种思路是直接在其中一颗树上操作,不申请任何新节点,只是修改指针指向(但是不知道为什么,此种方法提交后LeetCode上运行得比申请节点的方式慢?excuse me???????????????)
另一种思路是申请新节点并处理新键节点的每一个成员的方式。
暂时采用递归实现:
思路1详解:以t1作为基树,那么以t1的节点是否存在作为标准,如果t1不存在,使用t2的节点,如果t1的节点存在,则查看t2的节点是否存在,如果不存在什么都不做,如果t2的节点存在,那么使t1中的val域+=t2的val域。处理完成后递归处理,t1的左右子树,最后返回t1即可;
/** * 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) { merge(t1, t2); return t1; } void merge(TreeNode *&t1, TreeNode *t2) { if( nullptr == t1 ) t1 = t2; else { if( nullptr == t2 ) return; else { t1->val += t2->val; merge(t1->left, t2->left); merge(t1->right, t2->right); } } }};
思路2详解:分为三种情况处理,t1节点与t2节点均不存在,t1与t2均存在,任一树节点不存在。第一个情况在做参数判断时,可一并处理。不满足均为空时,可以申请节点了,接下来判断是两树节点均存在还是任一不存在,如果是两树均存在,则为新节点的val域赋值t1与t2的val域值之和,接下来递归处理新节点的左子树,右子树。当任一节点不为空时,返回不为空树节点
/** * 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( nullptr == t1 && nullptr == t2 ) { return nullptr; } TreeNode *t = new TreeNode(0); if( nullptr == t ) { return nullptr; } if( nullptr != t1 && nullptr != t2 ) { t->val = t1->val + t2->val; t->left = mergeTrees(t1->left, t2->left); t->right = mergeTrees(t1->right, t2->right); } else { if( nullptr != t1 ) { return t1; } else { return t2; } } return t; }};
明天上非递归解法。
- LeetCode二叉树合并
- leetcode二叉树合并非递归版本
- leetcode Merge Two Binary Trees 合并二叉树
- 【Leetcode】Merge Two Binary Trees 合并两个二叉树
- 【二叉树】合并二叉树
- LeetCode 617 Merge Two Binary Trees(递归合并二叉树)
- leetcode算法题2: 合并两个二叉树。递归,如何切入并保持清醒?
- LeetCode--Merge Two Binary Trees(合并两个二叉树)Python
- 合并两个二叉搜索树
- 合并两棵二叉树
- 合并俩棵二叉树
- 算法期中 合并二叉树
- leetcode:构建二叉树
- 重建二叉树 leetcode
- LeetCode -- Flatten 二叉树
- leetcode-构造二叉树
- leetcode二叉树遍历
- leetcode 重建二叉树
- 数据结构实验之串一:KMP简单应用
- 在云主机构建的hadoop集群上运行程序(接上一篇博文)
- C语言操作符 小结
- 过了很久终于我愿抬头看 你就在对岸等我勇敢
- php函数
- LeetCode二叉树合并
- Redis五种数据类型介绍
- 首次安装centos7后网络设置
- 55. Jump Game
- php数组
- php面对对象oop(object-oriented Programming)
- 易语言PUSH窗口法记录
- php GD库的使用:处理图像的功能
- 数据结构实验之串三:KMP应用