preorder . 144
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
if (root == null) {
return ans;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode head = stack.pop();
if (head.right != null) {
stack.push(head.right);
}
if (head.left != null) {
stack.push(head.left);
}
ans.add(head.val);
}
return ans;
}
}
inorder
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
if (root == null) {
return ans;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode curt = root;
while (curt != null || !stack.isEmpty()) {
while (curt != null) {
stack.push(curt);
curt = curt.left;
}
curt = stack.pop();
ans.add(curt.val);
curt = curt.right;
}
return ans;
}
}
postorder
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new LinkedList<>();
if (root == null) {
return ans;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode curt = stack.pop();
ans.add(0, curt.val);
if (curt.left != null) {
stack.push(curt.left);
}
if (curt.right != null) {
stack.push(curt.right);
}
}
return ans;
}
}
class Solution {
int ans;
int count;
public int kthSmallest(TreeNode root, int k) {
count = k;
helper(root);
return ans;
}
public void helper(TreeNode root) {
if (root == null || count == 0) {
return;
}
helper(root.left);
count--;
if (count == 0) {
ans = root.val;
}
helper(root.right);
}
}