Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes‘ values.
For example:
Given binary tree {1,#,2,3}
,
1 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
https://leetcode.com/problems/binary-tree-preorder-traversal/
树的先序遍历,不递归的方式,维护一个栈,先塞右子树,再塞左子树。
递归:
1 /** 2 * Definition for a binary tree node. 3 * function TreeNode(val) { 4 * this.val = val; 5 * this.left = this.right = null; 6 * } 7 */ 8 /** 9 * @param {TreeNode} root 10 * @return {number[]} 11 */ 12 var preorderTraversal = function(root) { 13 var res = []; 14 preorder(root); 15 return res; 16 17 function preorder(node){ 18 if(node && node.val !== undefined){ 19 res.push(node.val); 20 if(node.left !== null){ 21 preorder(node.left); 22 } 23 if(node.right !== null){ 24 preorder(node.right); 25 } 26 } 27 } 28 };
非递归:
1 /** 2 * @param {TreeNode} root 3 * @return {number[]} 4 */ 5 var preorderTraversal = function(root) { 6 var stack = [], res = [], curr; 7 if(root && root.val !== undefined){ 8 res.push(root.val); 9 if(root.right !== null){ 10 stack.push(root.right); 11 } 12 if(root.left !== null){ 13 stack.push(root.left); 14 } 15 } 16 while(stack.length !== 0){ 17 curr = stack.pop(); 18 res.push(curr.val); 19 if(curr.right !== null){ 20 stack.push(curr.right); 21 } 22 if(curr.left !== null){ 23 stack.push(curr.left); 24 } 25 } 26 return res; 27 };
时间: 2024-12-24 23:22:44