Skip to content
文档章节

BM32 合并二叉树

解法一

ts
/*class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 
 * @param t1 TreeNode类 
 * @param t2 TreeNode类 
 * @return TreeNode类
 */
export function mergeTrees(t1: TreeNode, t2: TreeNode): TreeNode {
    // write code here
  if(!t1 && !t2) return t1;
  if(!t1) return t2;
  if(!t2) return t1;
  
  t1.val = t1.val + t2.val;
  
  t1.left = mergeTrees(t1.left, t2.left);
  t1.right = mergeTrees(t1.right, t2.right);
  return t1;
}

层序遍历

ts
/*class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * @param t1 TreeNode类
 * @param t2 TreeNode类
 * @return TreeNode类
 */
export function mergeTrees(t1: TreeNode, t2: TreeNode): TreeNode {
  // write code here
  if(!t1) return t2;
  if(!t2) return t1;
  
  var head = new TreeNode(t1.val + t2.val);
  var list = [head]
  var list1 = [t1];
  var list2 = [t2];
  
  
  while(list1.length && list2.length) {
    var node = list.shift();
    var node1 = list1.shift();
    var node2 = list2.shift();
    
    let left1 = node1.left;
    let right1 = node1.right;
    let left2 = node2.left;
    let right2 = node2.right;
    
    if(left1 || left2) {
      if(left1 && left2) {
        var left = new TreeNode(left1.val + left2.val);
        node.left = left;
        
        list.push(left);
        list1.push(left1);
        list2.push(left2);
      } else if(left1) {
        node.left = left1;
      } else {
        node.left = left2;
      }
    }
    
    if(right1 || right2) {
      if(right1 && right2) {
        var right = new TreeNode(right1.val + right2.val);
        node.right = right;
        
        list.push(right);
        list1.push(right1);
        list2.push(right2);
      } else if(right1) {
        node.right = right1;
      } else {
        node.right = right2;
      }
    }
  }
  return head;
}