-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathbinarytree_preorder.java
More file actions
40 lines (38 loc) · 1.12 KB
/
binarytree_preorder.java
File metadata and controls
40 lines (38 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* 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> ans = new ArrayList<>();
// preorder(ans,root);
Stack<TreeNode> st = new Stack<>();
if(root==null) return ans;
st.push(root);
while(!st.isEmpty()){
TreeNode temp = st.pop();
ans.add(temp.val);
if(temp.right!=null)st.push(temp.right);
if(temp.left!=null)st.push(temp.left);
}
return ans;
}
// using recursion method
// public void preorder(List<Integer> list , TreeNode root){
// if(root==null) return;
// list.add(root.val);
// preorder(list,root.left);
// preorder(list,root.right);
// }
}