226. 翻转二叉树

题目链接

// 升级一下initTree的代码
const initTree = (inputList) => {
  const total = inputList.length;
  if(!inputList[0])return null;
  inputList[0] = new TreeNode(inputList[0]);
  inputList.forEach((el,index) => {
      let leftP = null;
      let rightP = null;
      if (!el) return;
      if (index*2+1 < total) {
          leftP = inputList[index*2+1]? new TreeNode(inputList[index*2+1]): null;
          inputList[index*2+1] = leftP;
      } 
      if (index*2+2 < total) {
          rightP = inputList[index*2+2]? new TreeNode(inputList[index*2+2]): null;
          inputList[index*2+2] = rightP;
      }
      inputList[index].left = leftP;
      inputList[index].right = rightP;
  });
  return inputList[0];
}

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 {TreeNode}
 */
var invertTree = function(root) {
  if(!root) {
    return root;
  }
  root.left = invertTree(root.left);
  root.right = invertTree(root.right);

  const temp = root.left;
  root.left = root.right;
  root.right = temp;
  return root;
};

// 验证代码
(()=>{
  const input = [3,9,20,null,null,15,7];
  const root = initTree(input);
  console.log('root', root);
  const res = invertTree(root);
  console.log('res', res);
})();

results matching ""

    No results matching ""