zoukankan      html  css  js  c++  java
  • 617.Merge Two Binary Trees 合并两个二叉树

    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) return t1;
    13. if (t2 == null) return t2;
    14. Merge(t1, t2);
    15. return t1;
    16. }
    17. public void Merge(TreeNode t1, TreeNode t2) {
    18. if (t1 != null && t2 != null) {
    19. t1.val = t1.val + t2.val;
    20. if (t1.left != null && t2.left != null) {
    21. Merge(t1.left, t2.left);
    22. }
    23. if (t1.right != null && t2.right != null) {
    24. Merge(t1.right, t2.right);
    25. }
    26. }
    27. if (t1.left == null && t2.left != null) {
    28. t1.left = t2.left;
    29. }
    30. if (t1.right == null && t2.right != null) {
    31. t1.right = t2.right;
    32. }
    33. }
    34. }





  • 相关阅读:
    docker 容器与主机之间的数据copy
    vim 中如何快速注释和取消注释
    java查找字符中的某个内容并替换
    linux正则表达式
    数据流重定向与管道命令
    linux杂七杂八
    linux变量
    redis常用命令操作
    redis基本操作介绍
    redis数据结构
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/87d4c41ce5602c033495e4f94fc62bdc.html
Copyright © 2011-2022 走看看