javaScript --牛客 NC45 实现二叉树先序,中序和后序遍历

题目描述
分别按照二叉树先序,中序和后序打印所有的节点。
在这里插入图片描述
二叉树的遍历主要有三种:

(1)先(根)序遍历(根左右)

(2)中(根)序遍历(左根右)

(3)后(根)序遍历(左右根)

/*
 * 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) return null;
    let pre = [],ino = [],last = [];
    function prefind( root){
    
    
    //if(root) return null;
        if(!root) {
    
    
            return null;
        }    
        pre.push(root.val);
        prefind(root.left);
        prefind(root.right);
        return pre;
}
    function infind( root){
    
    
    //if(root) return null;
        if(!root) {
    
    
            return null;
        }
        infind(root.left);
        ino.push(root.val);
        infind(root.right);
        return ino;
}
    function lastfind( root){
    
    
        if(!root) {
    
    
            return null;
        }
        lastfind(root.left);
        lastfind(root.right);
        last.push(root.val);
        return last;
}
     return [prefind(root),infind(root),lastfind(root)];
    
}
/*
 * 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) return null;
    return [prefind(root,[]),infind(root,[]),lastfind(root,[])];
}

function prefind( root,result ){
    
    
    //if(root) return null;
    if(!root) {
    
    
        return null;
    }
        result.push(root.val);
        prefind(root.left,result);
        prefind(root.right,result);
    return result;
}
function infind( root,result ){
    
    
    //if(root) return null;
    if(!root) {
    
    
        return null;
    }
        infind(root.left,result);
        result.push(root.val);
        infind(root.right,result);
    return result;
}
function lastfind( root,result ){
    
    
    if(!root) {
    
    
        return null;
    }
        lastfind(root.left,result);
        lastfind(root.right,result);
        result.push(root.val);
    return result;
}

猜你喜欢

转载自blog.csdn.net/sanjun_done/article/details/114550976