二叉树的前序遍历

递归解法

var result = []
function preorderTraversal( root ) {
    // write code here
    if(!root){return []}
    result.push(root.val)
    preorderTraversal(root.left)
    preorderTraversal(root.right)
    return result
}

迭代解法

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */

/**
  * 
  * @param root TreeNode类 
  * @return int整型一维数组
  */
function preorderTraversal( root ) {
    // write code here
    var stack = []
    var result = []
    var current = root
    while(current || stack.length){
        while(current){
            result.push(current.val)
            stack.push(current.right)
            current = current.left
        }
        current = stack.pop()
    }
    return result
}
module.exports = {
    preorderTraversal : preorderTraversal
};
树算法 文章被收录于专栏

树相关算法

全部评论

相关推荐

求过求过
xianwu543:华为不是线下面试吗?你怎么就面完了
点赞 评论 收藏
分享
真的很糟糕:不一定是你的问题,当然你也可以做的更好一些,继续投相信自己一定会有的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务