题解 | #实现二叉树先序,中序和后序遍历#

实现二叉树先序,中序和后序遍历

http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362

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

/**
 * 
 * @param root TreeNode类 the root of binary tree
 * @return int整型二维数组
 */
let pre = [];
let mid = [];
let post = [];
function threeOrders( root ) {
    
    if (root != null) {
        preorder(root);
        midorder(root);
        postorder(root);
    }
    const res = [pre, mid, post];
    return res;
}

function preorder(root) {
    if (root == null) {
        return;
    }
    pre.push(root.val);
    preorder(root.left);
    preorder(root.right);
}

function midorder(root) {
    if (root == null) {
        return;
    }
    midorder(root.left);
    mid.push(root.val);
    midorder(root.right);
}


function postorder(root) {
    if (root == null) {
        return;
    }
    postorder(root.left);
    postorder(root.right);
    post.push(root.val);
}

module.exports = {
    threeOrders : threeOrders
};
全部评论

相关推荐

仁者伍敌:服务员还要脱颖而出,这是五星级酒店吗
点赞 评论 收藏
分享
下北澤大天使:你是我见过最美的牛客女孩😍
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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