二叉树的中序遍历

递归解法

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

树相关算法

全部评论

相关推荐

菜鸡29号:根据已有信息能初步得出以下几点: 1、硕士排了大本和大专 2、要求会多语言要么是招人很挑剔要么就是干的活杂 3、给出校招薪资范围过于巨大,说明里面的薪资制度(包括涨薪)可能有大坑
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务