Skip to content

Commit

Permalink
144. 二叉树的前序遍历
Browse files Browse the repository at this point in the history
  • Loading branch information
cslc-ubm committed Jul 6, 2020
1 parent ef2c16b commit 5c8b8c6
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions 144. 二叉树的前序遍历.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,22 @@ var preorderTraversal = function (root) {
return result
};

// *** 迭代通用方法 *** 参见94中序遍历、145后序遍历
var preorderTraversal = function (root) {
let result = [], stack = [], cur
if (root) stack.push(root)
while (stack.length > 0) {
cur = stack.pop()
if (cur !== null) {
if (cur.right) stack.push(cur.right)
if (cur.left) stack.push(cur.left)
stack.push(cur)
stack.push(null)
} else {
result.push(stack.pop().val)
}
}
return result
};

var root = [1, null, 2, 3]

0 comments on commit 5c8b8c6

Please sign in to comment.