二叉树

65 阅读1分钟

image.png

前序遍历

function preorder(root, res){
    if(root == null){
        return ;
    }
    res.push(root.val);
    preorder(root.left, res); //前序
    preorder(root.right, res);
}
function preorderTraversal( root ) {
    // write code here
    let res = [];
    preorder(root, res);
    return res;
    
}

中序遍历

function inorder(root, res){
    if(root == null){
        return ;
    }
    inorder(root.left, res);
    res.push(root.val);
    inorder(root.right, res);
}

后续遍历

function postorder(root , res){
    if(root == null) return ;
    
    postorder(root.left, res);
    postorder(root.right, res);
    res.push(root.val);
}

层序遍历

一层放在数组同一位置

function levorder(root, res, level){
    if(root == null) return ;
    
    if(level >= res.length){
        res[level] = [];
    }
    res[level].push(root.val);
    levorder(root.left, res, level+1);
    levorder(root.right, res, level+1);
}
function levelOrder( root ) {
    // write code here
    let res = [];
    levorder(root, res , 0);
    return res;
}

之字形遍历

先从左往右,再从右往左

单数行进行数组反转

function order(root, res, level){
    if(root == null) return ;
    
    if(level >= res.length){
        res[level] = [];
    }
    
    res[level].push(root.val);
    order(root.left, res, level+1);
    order(root.right, res, level+1);
}
function Print(pRoot)
{
    // write code here
    let res = [];
    order(pRoot, res, 0);
    for(let i = 0; i < res.length; i++){
        if(i%2 == 1){
            res[i].reverse();
        }
    }
    return res;
}

二叉树深度

function order(root){
    if(root == null) return 0;
    
    return Math.max(order(root.left), order(root.right))+1;
}
function maxDepth( root ) {
    // write code here
    let ans = order(root);
    return ans;
}