//前序遍历
/**
* 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 {
List<Integer> res;
/*
//递归
public List<Integer> preorderTraversal(TreeNode root) {
res = new ArrayList<>();
recur(root);
return res;
}
public void recur(TreeNode root){
if(root == null)
return;
res.add(root.val);
recur(root.left);
recur(root.right);
}
*/
//非递归
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList();
Stack<TreeNode> stack = new Stack();
TreeNode cur = root;
while(cur != null || !stack.isEmpty()){
if(cur != null){
list.add(cur.val);
stack.push(cur);
cur = cur.left;
}else{
cur = stack.pop();
cur = cur.right;
}
}
return list;
}
}
//中序遍历
class Solution {
List<Integer> list = new ArrayList<>();
/*
//递归
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null)
return list;
inorderTraversal(root.left);
list.add(root.val);
inorderTraversal(root.right);
return list;
}
*/
//非递归
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack();
TreeNode cur = root;
while(cur != null || !stack.isEmpty()){
if(cur != null){
stack.push(cur);
cur = cur.left;
}else{
cur = stack.pop();
list.add(cur.val);
cur = cur.right;
}
}
return list;
}
}
//后序遍历
class Solution {
List<Integer> res = new ArrayList();
public List<Integer> postorderTraversal(TreeNode root) {
if(root == null)
return null;
postorderTraversal(root.left);
postorderTraversal(root.right);
res.add(root.val);
return res;
}
}
//层序遍历
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
if(root == null)
return new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
List<Integer> tmp = new ArrayList<>();
Integer length = queue.size();
for(int i = 0; i < length; i++){
TreeNode node = queue.poll();
tmp.add(node.val);
if(node.left != null)
queue.add(node.left);
if(node.right != null)
queue.add(node.right);
}
list.add(tmp);
}
return list;
}
}