码迷,mamicode.com
首页 > 其他好文 > 详细

617.Merge Two Binary Trees 合并两个二叉树

时间:2017-06-18 11:57:14      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:get   rom   ace   lang   enum   values   www   value   href   

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. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left;
  6. * public TreeNode right;
  7. * public TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public TreeNode MergeTrees(TreeNode t1, TreeNode t2) {
  12. if (t1 == null && t2 == null) {
  13. return null;
  14. } else if (t1 == null && t2 != null) {
  15. return t2;
  16. } else if(t1 != null && t2 == null) {
  17. return t1;
  18. }
  19. Merge(t1, t2);
  20. return t1;
  21. }
  22. public void Merge(TreeNode t1, TreeNode t2) {
  23. if (t1 != null && t2 != null) {
  24. t1.val = t1.val + t2.val;
  25. if (t1.left != null && t2.left != null) {
  26. Merge(t1.left, t2.left);
  27. }
  28. if (t1.right != null && t2.right != null) {
  29. Merge(t1.right, t2.right);
  30. }
  31. }
  32. if (t1.left == null && t2.left != null) {
  33. t1.left = t2.left;
  34. }
  35. if (t1.right == null && t2.right != null) {
  36. t1.right = t2.right;
  37. }
  38. }
  39. }





617.Merge Two Binary Trees 合并两个二叉树

标签:get   rom   ace   lang   enum   values   www   value   href   

原文地址:http://www.cnblogs.com/xiejunzhao/p/87d4c41ce5602c033495e4f94fc62bdc.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!