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

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

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
};
全部评论

相关推荐

10-29 15:38
门头沟学院 Java
榕城小榕树:难道你简历里写了配送路径优化算法?
点赞 评论 收藏
分享
AaronRuan:看到了好多开奖了,不知道为啥自己也有点激动,真的替你们感到高兴啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务