二叉树的前序遍历
给定一个二叉树,返回它的 前序 遍历。
示例:
解题思路
前序遍历:头节点->左子树->右子树
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
var arr = []
if(!root){
return arr
}
preorder(root)
return arr
function preorder(node){
arr.push(node.val)
if(node.left != null){
preorder(node.left)
}
if(node.right != null){
preorder(node.right)
}
}
};