翻转二叉树--写出来可以去google吗?

54 阅读1分钟

大部分人对这个题目觉得很简单,但是其实初步想法都下意识选择了前序遍历,但是假如我用中序遍历呢,可以实现吗

中序遍历

var invertTree = function(root) {
  if(root === null) return null;
  invertTree(root?.left)
  if(root.left !== null || root.right !== null){
    [root.left,root.right] = [root.right,root.left]
  }
  invertTree(root.left)
  return root

};

其实当中序遍历到根节点的时候,右子树早就已经被反转了,还是需要继续进行左子树的遍历 简单的题目,从另一个角度,方法做。

前序遍历呢

var invertTree = function(root) {
  if(root === null) return null;
  if(root.left !== null || root.right !== null){
    [root.left,root.right] = [root.right,root.left]
  }
  invertTree(root.left)
  invertTree(root.right)
  return root

};

层序遍历 待补充