Leetcode-Question-144: Binary Tree Preorder Traversal

原文链接:

https://leetcode.com/problems/binary-tree-preorder-traversal/

题目描述:

  1. Binary Tree Preorder Traversal
    Difficulty: Medium

Given a binary tree, return the preorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

解答:

法1) 俺的笨办法——

 

法2)Leetcode上得星30的解法,优雅!参考

https://leetcode.com/discuss/9734/accepted-code-explaination-with-algo

思路:

  1. Create an empty stack, Push root node to the stack.
  2. Do following while stack is not empty.

2.1. pop an item from the stack and print it.

2.2. push the right child of popped item to stack.

2.3. push the left child of popped item to stack.

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注