-
Notifications
You must be signed in to change notification settings - Fork 5
/
BinaryTreePreOrderTraversal.java
58 lines (53 loc) · 1.58 KB
/
BinaryTreePreOrderTraversal.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
Problem Statement:
Given a binary tree, return the preorder traversal of its nodes' values.
Problem Link:
Binary Tree Preorder Traversal:https://leetcode.com/problems/binary-tree-preorder-traversal/description/
Solution:
https://github.com/sunnypatel165/leetcode-again/blob/master/solutions/BinryTreePreOrderTraversal.java
Author:
Sunny Patel
https://github.com/sunnypatel165
https://www.linkedin.com/in/sunnypatel165/
*/
//////////////// RECURSIVE SOLUTION AT THE BOTTOM /////////////////
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root==null)
return list;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
if(node!=null){
list.add(node.val);
stack.push(node.right);
stack.push(node.left);
}
}
return list;
}
public List<Intger> preorderTraversalRecursive(TreeNode root){
if(root==null)
return list;
list.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
return list;
}
}
/*
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root==null)
return list;
list.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
return list;
}
}
*/