深度优先

 * 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 ) {
    let ans = []
    ans.push(pre(root).slice(),mid(root).slice(),post(root).slice())
    return ans
}

 //中
 function mid( root ) {
     let res = [];
     if(!root)    return res;
     let stack = [];
     let p = root;
     while(p || stack.length > 0){
         while(p){    //直至左节点为空,即没有左节点为止
             stack.push(p);
             p = p.left;
         }
         p = stack.pop();
         res.push(p.val);
         p = p.right;
     }
     return res;
 }
//先
 function pre( root ) {
     let res = [];
     if(!root)    return res;
     let stack = [];
     let p = root;
     while(p || stack.length > 0){
         while(p){
             res.push(p.val);
             stack.push(p);
             p = p.left;
         }
         p = stack.pop();
         p = p.right;
     }
     return res;
 }
 //后
 function post( root ) {
     let res = [];
     if(!root)    return res;
     let stack = [];
     let p = root;
     while(p || stack.length > 0){
         while(p){
             res.push(p.val);
             stack.push(p);
             p = p.right;
         }
         p = stack.pop();
         p = p.left;
     }
     return res.reverse();
 }
module.exports = {
    threeOrders : threeOrders
};

递归

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

/**
 * 
 * @param root TreeNode类 the root of binary tree
 * @return int整型二维数组
 */
let preArr = [],midArr = [],postArr = []
function threeOrders( root ) {
    let ans = []
    pre(root)
    mid(root)
    post(root)
    ans.push(preArr.slice(),midArr.slice(),postArr.slice())
    return ans
}
//中
function mid(root){
    if(!root)    return null
    mid(root.left)
    midArr.push(root.val)
    mid(root.right)
}
//前
function pre(root){
    if(!root)    return null
    preArr.push(root.val)
    pre(root.left)
    pre(root.right)
}
//后
function post(root){
    if(!root)    return null
    post(root.left)
    post(root.right)
    postArr.push(root.val)
}
module.exports = {
    threeOrders : threeOrders
};

alt