二叉树的中序遍历

递归解法

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

迭代解法

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

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

树相关算法

全部评论

相关推荐

02-26 18:25
已编辑
南京大学 算法工程师
点赞 评论 收藏
分享
lingo12:1.最好加个业务项目,大部分面试官工作以后会更偏重业务 2.实习部分描述一般般,可能hr看到会觉得你产出不够不给你过简历 3.蓝桥杯这些大部分人都有的,不如不写,反而减分项。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务