617. Merge Two Binary Trees
来源:互联网 发布:英国大城市知乎 编辑:程序博客网 时间:2024/06/05 19:05
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. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { TreeNode head = new TreeNode(0);head.left = t1;helper(t1, t2, head, false);return head.left; } public void helper(TreeNode t1, TreeNode t2, TreeNode head, boolean dire) {if (t1 == null && t2 == null)return;if (t1 != null && t2 != null) {t1.val += t2.val;helper(t1.left, t2.left, t1, false);helper(t1.right, t2.right, t1, true);} else if (t2 != null) {if (dire)head.right = t2;elsehead.left = t2;}}}
阅读全文
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
- UGUI 如何激活InputField并使脱字符号放到最后一个字符的位置
- SVN中报错 “Previous operation has not finished; run 'cleanup' if it was interrupted” 的解决办法
- ELK学习6_Kafka->Logstash->Elasticsearch数据流操作
- ssd与基于ssd的文件系统
- 基于Python的K-means聚类算法
- 617. Merge Two Binary Trees
- Android MediaCodec解码aac,播放.
- java源码分析之LinkedList
- AndroidStudio 启动模拟器
- JPA 一对多 OneToMany 注解
- ELK学习7_ELK文档资料:《ELK stack 权威指南/饶琛琳》勘误
- Java学习笔记--javascript入门
- redis配置文件讲解
- Ibatis 中关于sql动态传值问题