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

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

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

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */
let preOrderArr = []    // 先
let inOrderArr = []     // 中
let postOrderArr = []   // 后

// 先序
function preOrder (node) {
  if (node !== null) {
    preOrderArr.push(node.val)
    preOrder(node.left)
    preOrder(node.right)
  }
}

// 中序
function inOrder (node) {
  if (node !== null) {
    inOrder(node.left)
    inOrderArr.push(node.val)
    inOrder(node.right)
  }
}

// 后序
function postOrder (node) {
  if (node !== null) {
    postOrder(node.left)
    postOrder(node.right)
    postOrderArr.push(node.val)
  }
}

/**
 * 
 * @param root TreeNode类 the root of binary tree
 * @return int整型二维数组
 */
function threeOrders( root ) {
  preOrder(root)
  inOrder(root)
  postOrder(root)
  
  return [preOrderArr, inOrderArr, postOrderArr]
}
module.exports = {
    threeOrders : threeOrders
};
全部评论

相关推荐

点赞 评论 收藏
分享
安静的鲸鱼offer...:神仙级别hr,可遇不可求,甚至他可能也是突然有感而发。只能说遇上是件幸事。
秋招开始捡漏了吗
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

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