题解 | #二叉树的前序遍历#

二叉树的前序遍历

http://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635

二叉树的递归和非递归解法

递归解法

一定要注意res的全局性,作为参数要被传入;要注意递归的出口;

function preorderTraversal( root ) {
    // write code here
    const res = [];
    preorder(root,res);
    return res;
    
}
function preorder(root,res){
    if(!root){return;}
    res.push(root.val);
    preorder(root.left,res);
    preorder(root.right,res);
}
module.exports = {
    preorderTraversal : preorderTraversal
};

非递归解法

一定要注意当root为空的时候的返回

function preorderTraversal( root ) {
    let res = [];
    if(!root) return res;
    let stk = [root];
    while(stk.length){
        let top = stk.pop();
        res.push(top.val);
       if(top.right) stk.push(top.right);
       if(top.left) stk.push(top.left);
    }
    return res;
    
}
全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务