[리트코드] 617. Merge Two Binary Trees




617. Merge Two Binary Trees

리트코드 문제 바로가기

나의 풀이

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root1
 * @param {TreeNode} root2
 * @return {TreeNode}
 */
var mergeTrees = function (root1, root2) {
  if (!root1) return root2;
  if (!root2) return root1;
  root1.val += root2.val;
  root1.left = mergeTrees(root1.left, root2.left);
  root1.right = mergeTrees(root1.right, root2.right);
  return root1;
};



102. Binary Tree Level Order Traversal

리트코드 문제 바로가기

나의 풀이

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
 var levelOrder = function(root) {
  let result = [];
  let currentLevelNodes = [];
  if(root)
      currentLevelNodes.push(root);
  while(currentLevelNodes.length > 0) {
      current = [];
      let len = currentLevelNodes.length;
      console.log(len, currentLevelNodes)
      for (let i = 0; i< len; i++) {
          let node = currentLevelNodes.shift();
          console.log(node)
          current.push(node.val);
          if(node.left) {
              currentLevelNodes.push(node.left);
          }
          if(node.right) {
              currentLevelNodes.push(node.right);
          }
      }
      result.push(current);
  }
  return result;
};

// 1 [ [3,9,20,null,null,15,7] ]
// [3,9,20,null,null,15,7]
// 2 [ [9], [20,15,7] ]
// [9]
// [20,15,7]
// 2 [ [15], [7] ]
// [15]
// [7]