144. Binary Tree Preorder Traversal
# Medium, DFS
Solution 1: Non-recursive
This is "while loop" method using stack
Use a list as stack, stack.pop() moves top element, stack.append() pushes element to top. Because Python doesn't have stack data structure
Append root to result list directly, push right leaf to stack, then push left leaf to stack
Poop out an element, which is a new root so append it to result list, then push its right leaf to stack, then push left leaf to stack
Until stack is empty
add root.val to result list instead of root, but operate root/left/right in stack list
Solution 2: Recursive
Using help function to do recurcive, result list as one of two parameters, when root=None, return
Add root, traversal left, then right
return
result
at the end of whole functions
Self define a traversal function, pass "root" and "result", so that "result" can be changed following recursive
Add root.val to result, and traversal left, then right
When root=None, return from sub-function
return result in main function
In sub-function, only return and pass result list as a parameter; In main function, return result list???
If return result list in sub-function, it is useless because result has been passed as a parameter. In main function, if return sub-function, then the result list will be None.Because it only returns initial result lis. Why? I tried, but don't know why.
Solution 3: Divide & Conquer
Recursive the function itself, return result during recursive
Traversal left, right, and combine root, left, right at the end
return
result
immediately in each recursion
Initialize result list
Return result list if satisfied stop condition
Divide binary tree to root, left and right
Conquer to do recursive
Combine them again to get the completed result
When combine, using result.extend()
instead of result.append()
. Because extend
means only add the elements of that list to another list, but append
adds whole list directly
Last updated
Was this helpful?