二叉树的中序遍历

递归解法

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

树相关算法

全部评论

相关推荐

牛油果甜奶昔:别的先不说,牛客还能内推护士?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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