JavaScript 结题(普通解法)

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

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

JavaScript 结题(普通解法)

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

/**
 * 
 * @param root TreeNode类 the root of binary tree
 * @return int整型二维数组
 */
function threeOrders( root ) {
    // write code here
    if (root === null) {
        return [];
    }
    var result = [];
    result.push(preTravesal(root));
    result.push(inTravesal(root));
    result.push(postTravesal(root));
    return result;
}

function preTravesal(root, result = []) {
    if (root !== null) {
        result.push(root.val);
        preTravesal(root.left, result);
        preTravesal(root.right, result);
    }
    return result;
}

function inTravesal(root, result = []) {
    if (root !== null) {
        inTravesal(root.left, result);
        result.push(root.val);
        inTravesal(root.right, result);
    }
    return result;
}

function postTravesal(root, result = []) {
    if (root !== null) {
        postTravesal(root.left, result);
        postTravesal(root.right, result);
        result.push(root.val);
    }
    return result;
}

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

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务