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:Iterative version 用stack
递归的就不写了,实在太简单。
用stack的方法的关键点在于,每一条路劲在探寻最左元素的时候,要把所有的parent node都push到stack中。
如果当前的路径到头了之后,从stack里pop出上一个parent,然后移步到右边。
注意终止条件是需要node!= null同时stack不为空。
C++
Java