二叉树
二叉树深度优先遍历(DFS)用栈
中序遍历(递归)
class TreeNode{
TreeNode left;
TreeNode right;
int val;
public TreeNode(int val) {
this.val = val;
}
}
public void infixOrder(TreeNode root){
if(root != null) {
System.out.println(root.val);
infixOrder(root.left);
infixOrder(root.right);
}
}
中序遍历(非递归)
public void infixOrder(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
if(root == null) return;
while(root != null || !stack.isEmpty()){
while(root != null){//一直遍历直到左子树叶子节点
stack.push(root);//根节点入栈
root = root.left;
}
if(!stack.isEmpty()){
root = stack.pop();//弹出左子树叶子节点
System.out.println(root.val);
root = root.right;
}
}
}
前序遍历
前序遍历和中序唯一不同是输出的时机,前序根节点入栈即输出
public class preOrder {
public void preOrder(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
if(root == null) return;
while(root != null || !stack.isEmpty()){
while(root != null){//一直遍历直到左子树叶子节点
stack.push(root);//根节点入栈
System.out.println(root.val);
root = root.left;
}
root = stack.pop();//弹出左子树叶子节点
root = root.right;
}
}
}
后序遍历
与前、中序不同,有一个指针保存上一个访问过的节点
public void postOrder(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
TreeNode pre = null;
while(cur != null || !stack.isEmpty()){
stack.push(cur);
cur = cur.left;
}
cur = stack.peek();
if(cur.right == null || cur.right == pre){
cur = stack.pop();
System.out.println(cur.val);
pre = cur;
cur = null;
}else{
cur = cur.right;
}
}
二叉树广度优先遍历(BFS)用队列
public void levelOrder(TreeNode root){
Queue<TreeNode> queue = new LinkedList<>();
if(root != null){
queue.offer(root);
}
while (!queue.isEmpty()){
int n = queue.size();//记录每层节点数,防止其他层节点入队影响本层节点输出
for(int i = 0; i < n; i++){
TreeNode node = queue.poll();//去除本层节点
System.out.println(node.val);
if(root.left != null) queue.offer(root.left);//下层左右节点入队
if(root.right != null) queue.offer(root.right);
}
}
}