Skip to content

Commit 740ca20

Browse files
committed
leetcode solution
1 parent 5e57f3a commit 740ca20

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

binary-tree-preorder-traversal.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,39 @@ function preorderTraversalBuilder(node, ret) {
2626
preorderTraversalBuilder(node.left, ret);
2727
preorderTraversalBuilder(node.right, ret);
2828
}
29+
30+
// Solution 2
31+
// Iterative Way
32+
/**
33+
* Definition for a binary tree node.
34+
* function TreeNode(val) {
35+
* this.val = val;
36+
* this.left = this.right = null;
37+
* }
38+
*/
39+
/**
40+
* @param {TreeNode} root
41+
* @return {number[]}
42+
*/
43+
var preorderTraversal = function (root) {
44+
if (root === null) {
45+
return [];
46+
}
47+
48+
var stack = [root];
49+
var ret = [];
50+
51+
while (stack.length > 0) {
52+
var cur = stack.pop();
53+
ret.push(cur.val);
54+
55+
if (cur.right) {
56+
stack.push(cur.right);
57+
}
58+
59+
if (cur.left) {
60+
stack.push(cur.left);
61+
}
62+
}
63+
return ret;
64+
};

0 commit comments

Comments
 (0)