-
Notifications
You must be signed in to change notification settings - Fork 0
/
LeetCode1.java
44 lines (43 loc) · 1.04 KB
/
LeetCode1.java
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
41
42
43
44
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) {
Stack<TreeNode> q=new Stack<>();
List<Integer> list=new ArrayList<>();
if(root==null)
{
return list;
}
q.push(root);
while(!q.isEmpty())
{
TreeNode node=q.pop();
list.add(node.val);
if(node!=null && node.right!=null)
q.push(node.right);
if(node!=null && node.left!=null)
q.push(node.left);
}
return list;
}
}
class LeetCode1
{
public static void Main(String args[])
{
TreeNode root;
//create a Binary Tree
//leet Code challage
System.out.print(new Solution().preorderTraversal(root));
}
}