144. 二叉树的前序遍历【简单题】
题目地址
function TreeNode(val,left,right) {
this.val = (val===undefined ? 0 : val);
this.left = (left===undefined ? null : left);
this.right = (right===undefined ? null: right);
}
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;
}
var preorderTraversal = function(root) {
return action(root, []);
}