-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path144.binary-tree-preorder-traversal.java
87 lines (76 loc) · 2.07 KB
/
144.binary-tree-preorder-traversal.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import javax.swing.tree.TreeNode;
import jdk.nashorn.api.tree.IfTree;
/*
* @lc app=leetcode id=144 lang=java
*
* [144] Binary Tree Preorder Traversal
*/
// @lc code=start
/**
* 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> res = new ArrayList<>();
// preorder(root, res);
// return res;
// }
// public void preorder(TreeNode root, List<Integer> res) {
// if (root == null) {
// return;
// }
// res.add(root.val);
// preorder(root.left, res);
// preorder(root.right, res);
// }
// }
// class Solution {
// public List<Integer> preorderTraversal(TreeNode root) {
// List<Integer> res = new ArrayList<>();
// Deque<TreeNode> stack = new LinkedList<>();
// while (root != null || !stack.isEmpty()) {
// while (root != null) {
// res.add(root.val);
// stack.push(root);
// root = root.left;
// }
// root = stack.pop();
// root = root.right;
// }
// return res;
// }
// }
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
TreeNode curr = root, pre = null;
while (curr != null) {
pre = curr.left;
if (pre != null) {
while (pre.right != null && pre.right != curr) {
pre = pre.right;
}
if (pre.right == null) {
res.add(curr.val);
pre.right = curr;
curr = curr.left;
continue;
} else {
pre.right = null;
}
} else {
res.add(curr.val);
}
curr = curr.right;
}
return res;
}
}
// @lc code=end