1. 程式人生 > >617. Merge Two Binary Trees(Tree)

617. Merge Two Binary Trees(Tree)

https://leetcode.com/problems/merge-two-binary-trees/description/

題目:合併2棵二叉樹

思路:採用後序遍歷的方法,分為3種情況:

1 如果t1非空並且t2非空,則t1加上t2的值,返回t1,否則直接返回t1
2 t1為空且t2非空,返回t2
3 t1和t2都為空,返回NULL

程式碼:

class Solution {
public:
    TreeNode *dfs(TreeNode* t1,TreeNode* t2){
              if(!t1&&!t2) return NULL
; TreeNode *left = dfs((t1?t1->left:NULL),(t2?t2->left:NULL)); TreeNode *right = dfs((t1?t1->right:NULL),(t2?t2->right:NULL)); if(t1){ t1->val+=(t2?t2->val:0); t1->left = left; t1->
right = right; } else return t2; return t1; } TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { t1 = dfs(t1,t2); return t1; } };