static 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;
}
}
先序遍历
/**
* 先序遍历
* @param root
* @return
*/
public static List<Integer> inorderTraversal2(TreeNode root) {
ArrayList<Integer>list=new ArrayList<>();
Stack<TreeNode> stack=new Stack<>();
stack.push(root);
while (!stack.isEmpty()){
TreeNode node = stack.pop();
System.out.print(node.val);
if(node.right!=null) stack.push(node.right);
if(node.left!=null) stack.push(node.left);
}
return list;
}
中序遍历
/**
* 中序遍历
* @param root
* @return
*/
public static List<Integer> inorderTraversal0(TreeNode root) {
ArrayList<Integer>list=new ArrayList<>();
Stack<TreeNode> stack=new Stack<>();
TreeNode cur = root;
Stack<Integer> num = new Stack<>();
while (cur!=null||!stack.isEmpty()){
if(cur!=null){
stack.push(cur);
cur = cur.left;
}else {
cur = stack.pop();
System.out.print(cur.val);
cur = cur.right;
}
}
return list;
}
后序遍历
采用双压栈的方式,第二次弹出时才打印自己值
/**
* 后续遍历
* @param current
* @return
*/
public static List<Integer> inorderTraversal3(TreeNode current) {
ArrayList<Integer>list=new ArrayList<>();
Stack<TreeNode> stack=new Stack<>();
stack.push(current);
stack.push(current);
while (!stack.isEmpty()) {
current = stack.pop();
if (!stack.isEmpty() && current == stack.peek()) {
if (current.right != null) {
stack.push(current.right);
stack.push(current.right);
}
if (current.left!= null) {
stack.push(current.left);
stack.push(current.left);
}
} else {
System.out.print(current.val);
}
}
return list;
}