問題:
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.
心得:
這題就是把兩個二元樹合併,我就想著最簡單遞迴來解決,看了最佳解答才發現如果為一邊null的話就可以直接用另外一邊來return更有效率,學習了。
我的答案:
public class Solution { public TreeNode MergeTrees(TreeNode t1, TreeNode t2) { if (t1 == null && t2 == null) { return null; } int t1Val = (t1 == null) ? 0 : t1.val; int t2Val = (t2 == null) ? 0 : t2.val; return new TreeNode(t1Val + t2Val) { left = MergeTrees(t1?.left, t2?.left), right = MergeTrees(t1?.right, t2?.right) }; } }
最佳解答:
public class Solution { public TreeNode MergeTrees(TreeNode t1, TreeNode t2) { if (t1 == null) { return t2; } if (t2 == null) { return t1; } return new TreeNode(t1.val + t2.val) { left = MergeTrees(t1.left, t2.left), right = MergeTrees(t1.right, t2.right) }; } }