LeetCode-Merge Two Binary Trees
阿新 • • 發佈:2018-12-10
** Description:** 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.
題意:給定兩顆二叉樹,要求將兩顆樹合併成一顆二叉樹;合併的規則是將兩顆樹對應節點的值相加(如果這個節點存在的話);
解法:這道題主要的難點就在於怎麼處理空節點;因為兩棵樹相同位置上節點可能都存在,也可能只有一顆存在;既然要求新的節點是兩個節點值的和,那麼如果一棵樹對應位置沒有節點,我們可以構造一個值為0的節點進行求和計算;
Java
/** * 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(TreeNode t1, TreeNode t2) { if (t1 == null && t2 == null) { return null; } TreeNode root = new TreeNode(0); if (t1 != null) root.val += t1.val; else t1 = new TreeNode(0); if (t2 != null) root.val += t2.val; else t2 = new TreeNode(0); root.left = mergeTrees(t1.left, t2.left); root.right = mergeTrees(t1.right, t2.right); return root; } }