Open CONNLY-J opened 4 years ago
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} t1 * @param {TreeNode} t2 * @return {TreeNode} */ var mergeTrees = function(t1, t2) { if(t1 == null){ return t2; } else if(t2 == null){ return t1; }else{ t1.val = t1.val + t2.val; t1.left = mergeTrees(t1.left,t2.left); t1.right = mergeTrees(t1.right,t2.right); return t1; } };
解题思路:根据二叉树的遍历合并节点 选定一棵树如t1,将t2合并到t1上; 若t1为空则直接返回t2,t2为空则直接返回t1; 若不为空,分别递归左子树和右子树,将节点值相加
解题思路:根据二叉树的遍历合并节点 选定一棵树如t1,将t2合并到t1上; 若t1为空则直接返回t2,t2为空则直接返回t1; 若不为空,分别递归左子树和右子树,将节点值相加