Java実装LeetCode 617マージバイナリツリー(木ウォーキング)

617マージバイナリツリー

あなたがカバーにお互いにそれらを想像して2つのバイナリツリーを考えると、いくつかのノードは、2つのバイナリツリーをオーバーラップします。

あなたは、新しいバイナリツリーにマージする必要があります。ルールの統合は、2つのノードが重複する場合、それらの値は、合併ノードの後に​​新しい値として追加され、またはノードがバイナリツリーとして新しいノードを指示するNULLでないことです。

例1:

入力:

Tree 1                     Tree 2                  
      1                         2                             
     / \                       / \                            
    3   2                     1   3                        
   /                           \   \                      
  5                             4   7         

出力:
複合ツリー:

     3
    / \
   4   5
  / \   \ 
 5   4   7

注意:合併は、ルートからの2つのツリーを起動する必要があります。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
       public TreeNode mergeTrees_1(TreeNode t1, TreeNode t2) {
        if (t1 == null) {
            return t2;
        }
        if (t2 == null) {
            return t1;
        }
        // 先合并根节点
        t1.val += t2.val;
        // 再递归合并左右子树
        t1.left = mergeTrees(t1.left, t2.left);
        t1.right = mergeTrees(t1.right, t2.right);
        return t1;
    }

    /**
     * 不修改原二叉树的解法
     */
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if (t1 == null && t2 == null) {
            return null;
        }
        // 先合并根节点
        TreeNode root = new TreeNode((t1 == null ? 0 : t1.val) + (t2 == null ? 0 : t2.val));
        // 再递归合并左右子树
        root.left = mergeTrees(t1 == null ? null : t1.left, t2 == null ? null : t2.left);
        root.right = mergeTrees(t1 == null ? null : t1.right, t2 == null ? null : t2.right);
        return root;
    }
}
リリース1675元の記事 ウォンの賞賛20000 + ビュー318万+

おすすめ

転載: blog.csdn.net/a1439775520/article/details/105201153