今日的题目,我之前文章有写过,前序中序后序都在这篇文章里 js实现二叉树的前序遍历,中序遍历,后续遍历
递归法
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
let arr = [];
(function preorderTraversalH(node){
if(node === null) return node;
arr.push(node.val);
preorderTraversalH(node.left);
preorderTraversalH(node.right);
})(root);
return arr;
};;
栈的方法
var preorderTraversal = function(root) {
if(root === null) return [];
let arr = [], stack = [];
let node = root;
// 先父节点再左节点再右节点,所以让右节点进栈
while(node){
arr.push(node.val);
if(node.right) stack.push(node.right);
if(node.left){
node = node.left;
} else {
node = stack.pop();
}
}
return arr;
}
网友评论