二叉树的中序遍历

递归解法

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

树相关算法

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-10 14:10
啊啊啊啊好幸福,妈妈是我找工作发疯前的一束光
榕城小榕树:你是我见过最幸福的牛客男孩
点赞 评论 收藏
分享
屌丝逆袭咸鱼计划:心态摆好,man,晚点找早点找到最后都是为了提升自己好进正职,努力提升自己才是最关键的😤难道说现在找不到找的太晚了就炸了可以鸡鸡了吗😤早实习晚实习不都是为了以后多积累,大四学长有的秋招进的也不妨碍有的春招进,人生就这样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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