144. 二叉树的前序遍历【简单题】

题目地址

function TreeNode(val,left,right) {
    this.val = (val===undefined ? 0 : val);
    this.left = (left===undefined ? null : left);
    this.right = (right===undefined ? null: right);
}

/**
 * 还原一棵满二叉树(似乎和题目用例不太一样?)
 * @param {number[]} valList 
 * @returns {TreeNode root}
 */
function initTree(valList) {
    const treeNodeList = [];
    const sum = valList.length;
    valList.forEach((el, index) => {
        if (!el) {
            treeNodeList.push(null);
            return;
        }
        const leftIndex = index*2+1 < sum ? index*2+1: null;
        const  rightIndex = index*2+2 < sum ? index*2+2 :null;
        const newNode = new TreeNode(el, leftIndex, rightIndex);
        treeNodeList.push(newNode);
    });
    treeNodeList.forEach(node=>{
        if(node && node.left) {
            node.left = treeNodeList[node.left];
        }
        if(node && node.right){
            node.right = treeNodeList[node.right];
        }
    });
    return treeNodeList[0];
}

function action(curNode, curRes) {
    if (!curNode) {
        return curRes;
    }
    curRes.push(curNode.val);
    curRes = action(curNode.left, curRes);
    curRes = action(curNode.right, curRes);
    return curRes;
}

/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function(root) {
    return action(root, []);
}

// 验证代码
// function validate() {
//     const input = [1,2,3];
//     const root = initTree(input);
//     console.log('root', root);
//     const result = preorderTraversal(root);
//     console.log(result);
// }

// validate();

results matching ""

    No results matching ""