-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 0 ms (100.00%), Space: 40.7 MB (40.20%) - LeetHub
- Loading branch information
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
33 changes: 33 additions & 0 deletions
33
0144-binary-tree-preorder-traversal/0144-binary-tree-preorder-traversal.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
/** | ||
* Definition for a binary tree node. | ||
* public class TreeNode { | ||
* int val; | ||
* TreeNode left; | ||
* TreeNode right; | ||
* TreeNode() {} | ||
* TreeNode(int val) { this.val = val; } | ||
* TreeNode(int val, TreeNode left, TreeNode right) { | ||
* this.val = val; | ||
* this.left = left; | ||
* this.right = right; | ||
* } | ||
* } | ||
*/ | ||
class Solution { | ||
public List<Integer> preorderTraversal(TreeNode root) { | ||
List<Integer> list = new ArrayList<>(); | ||
Stack<TreeNode> st = new Stack<>(); | ||
TreeNode node = root; | ||
|
||
while(node !=null || !st.isEmpty()){ | ||
while(node != null){ | ||
st.push(node); | ||
list.add(node.val); | ||
node = node.left; | ||
} | ||
node=st.pop(); | ||
node = node.right; | ||
} | ||
return list; | ||
} | ||
} |