leetcode[Merge Two Binary Trees]
2017-08-22 16:14
471 查看
解法一:就是根据两棵树,遍历的时候往下走,一棵没有的结点用另一棵的结点补上,两棵都没有的就为null,两棵都有的就求个和
/** * 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) { TreeNode root = null; if(t1 == null && t2 == null){ return root; } int val = (t1 == null ? 0 : t1.val) + (t2 == null ? 0 : t2.val); root = new TreeNode(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; } }
相关文章推荐
- Merge Two Binary Trees [LeetCode 617]
- LeetCode 617 Merge Two Binary Trees(递归合并二叉树)
- 【Leetcode】【python】Hamming Distance, Merge Two Binary Trees
- leetcode 617 merge two binary trees
- LeetCode(617) Merge Two Binary Trees
- Merge Two Binary Trees(leetcode)
- leetcode(617):Merge Two Binary Trees
- 【leetcode】 Merge Two Binary Trees
- 【Leetcode-easy-617】Merge Two Binary Trees
- leetcode(617):Merge Two Binary Trees
- Merge Two Binary Trees[LeetCode]
- LeetCode@Tree_617_Merge_Two_Binary_Trees
- leetcode(617). Merge Two Binary Trees
- lintcode/leetcode由易至难第15题:Merge Two Binary Trees
- leetcode 617 Merge Two Binary Trees
- [LeetCode] Merge Two Binary Trees 合并二叉树
- LeetCode - Merge Two Binary Trees
- leetcode之Merge Two Binary Trees
- [LeetCode]Merge Two Binary Trees
- LeetCode-617-Merge Two Binary Trees-E