二叉树的遍历
1.递归写法
先序遍历
public void preOrder(TreeNode root) {
if (root == null)
return;
System.out.print(root.val + " ");
preOrder(root.left);
preOrder(root.right);
}
中序遍历
public void inOrder(TreeNode root) {
if (root == null)
return;
preOrder(root.left);
System.out.print(root.val + " ");
preOrder(root.right);
}
后续遍历
public void afterOrder(TreeNode root) {
if (root == null)
return;
preOrder(root.left);
preOrder(root.right);
System.out.print(root.val + " ");
}
2.非递归写法
先序遍历
public void preOrder1(TreeNode root) {
Stack<TreeNode> stack=new Stack<>();
TreeNode currNode=root;
if(currNode!=null) {
stack.push(currNode);
while(!stack.isEmpty()) {
currNode=stack.pop();
System.out.print(currNode.val+" ");
if(currNode.right!=null) {
stack.push(currNode.right);
}
if(currNode.left!=null) {
stack.push(currNode.left);
}
}
}
}
中序遍历
public void inOrder1(TreeNode root) {
Stack<TreeNode> stack=new Stack<>();
TreeNode currNode=root;
while(currNode!=null||!stack.isEmpty()) {
while(currNode!=null) {
stack.push(currNode);
currNode=currNode.left;
}
if(!stack.isEmpty()) {
currNode=stack.pop();
System.out.print(currNode.val+" ");
currNode=currNode.right;
}
}
}
后续遍历
public void afterOrder1(TreeNode root) {
Stack<TreeNode> stack1=new Stack<>();
Stack<TreeNode> stack2=new Stack<>();
TreeNode currNode=root;
while(currNode!=null||!stack1.isEmpty()) {
while(currNode!=null) {
stack1.push(currNode);
stack2.push(currNode);
currNode=currNode.right;
}
if(!stack1.isEmpty()) {
currNode=stack1.pop();
currNode=currNode.left;
}
}
while(!stack2.isEmpty()) {
currNode=stack2.pop();
System.out.print(currNode.val+" ");
}
}
3.层序遍历
public void levelOrder(TreeNode root) {
if (root == null)
return;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
TreeNode temp = q.poll();
System.out.print(temp.val + " ");
if (temp.left != null) {
q.offer(temp.left);
}
if (temp.right != null) {
q.offer(temp.right);
}
}
}