用非递归的方式写前中后序遍历

前序

var preorderTraversal = function(root) {
    let res = [], stack = [];
    if(root==null) return res;
    stack.push(root);
    while(stack.length!=0){
        let x=stack.pop();
        res.push(x.val);
        if(x.right!=null){
            stack.push(x.right);
        }
        if(x.left!=null){
            stack.push(x.left);
        }
    }
    return res;
};

中序

const inorderTraversal = (root) => {
    let stack=[], res=[];
    while(stack.length!=0 || root!=null){
        while(root){
            stack.push(root);
            root=root.left;
        }
        let node = stack.pop();
        res.push(node.val);
        if(node.right!=null){
            root=node.right;
        }
    }
    return res;
}

后序

const postorderTraversal = (root) => {
    let stack=[], res=[];
    let prev = null;
    while(stack.length!=0 || root!=null){
        while(root){
            stack.push(root);
            root=root.left;
        }
        let node = stack.pop();
        if(node.right==null || node.right==prev){
            res.push(node.val);
            prev=node;
        }else{
            stack.push(node);
            root=node.right;
        }
    }
    return res;
}

遇到了Cannot access "variable_name" before initialization的问题,原因是在scope里面重新定义了之前已经定义的变量,在锁区里面又用了这个变量

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容