二叉树的中序遍历

递归解法

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
};
树算法 文章被收录于专栏

树相关算法

全部评论

相关推荐

哈哈哈哈哈哈哈哈哈哈这个世界太美好了
凉风落木楚山秋:毕业出路老师不管,你盖个章他好交差就完事了,等你盖完毕业了就不关他事情了
点赞 评论 收藏
分享
MinJerous:虽然我一直说 计算机不怎么卡学历 但是至少得一本
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 12:23
转人工😡
门口唉提是地铁杀:五次握手了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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