console.log问题,交换二叉树左右节点,交换前后输出相同结果

代码如下:

class Tree {
    constructor(left=null, right=null){
        this.v = id++;
        this.left = left;
        this.right = right;
    }

    switch() {
        if(null != this.left || null != this.right){
            let temp = this.right;
            this.right = this.left;
            this.left = temp;
        }
        if (null != this.left) {
            this.left.switch();
        }
        if (null != this.right) {
            this.right.switch();
        }
    }
}

var id = 0;

var A = new Tree();
var B = new Tree();
var C = new Tree(A, B);

var D = new Tree();
var E = new Tree(D);

var F = new Tree(C, E);
console.log(F);
F.switch();
console.log(F);

控制台为什么都输出交换后的结果?求解

阅读 2.3k
2 个回答

应该是你看错了…… 你用 console.log(JSON.stringify(F)); 看看

在Chrome上运行时被存了,页面加载完成后打印了缓存的数值,所以是一样的。
Chrome运行截图

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题