前序
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里面重新定义了之前已经定义的变量,在锁区里面又用了这个变量