Six traversal methods of binary tree (console output represents access)
1. Recursive preamble
public void recursion_pre(TreeNode root) { if (root==null) return; System.out.print(root.val); recursion_pre(root.left); recursion_pre(root.right); }
2. Recursive middle order
public void recursion_in(TreeNode root) { if (root==null) return; recursion_in(root.left); System.out.print(root.val); recursion_in(root.right); }
3. Recursive postorder
public void recursion_post(TreeNode root) { if (root==null) return; recursion_post(root.left); recursion_post(root.right); System.out.print(root.val); }
It can be seen that it is very simple to use recursive method to traverse the binary tree. The disadvantage is that if the binary tree is too large and the recursion level is too deep, it is easy to overflow. The following is a non recursive method implemented by stack structure.
4. Non recursive preamble
It's also very simple to traverse non recursively, first visit the root node, and at the same time, the right child enters the stack first, and the left child enters the stack later
public void noRecursion_pre(TreeNode root) { Stack<TreeNode> s=new Stack<>(); if (root!=null) s.push(root); while (!s.isEmpty()) { TreeNode cur=s.pop(); System.out.print(cur.val); if (cur.right!=null) s.push(cur.right); if (cur.left!=null) s.push(cur.left); } }
5. Non recursive middle order
Middle order traversal is left - > root - > right. In this process, we need to pass a node twice. The first time is to get its left child, and the second time is to visit the left child to access the node and find its right child. Therefore, first push the left child into the stack in turn until there is no left child. At this time, access the top node of the stack and loop the method above the right child.
public void noRecursion_in(TreeNode root) { if (root==null) return; Stack<TreeNode> s=new Stack<>(); TreeNode cur=root; while (!s.isEmpty() || cur!=null) { while (cur!=null) { s.push(cur); cur=cur.left; } if (!s.isEmpty()) { cur=s.pop(); System.out.print(cur.val); cur=cur.right; } } }
6. Non recursive postorder
There are many ways to implement non recursive post order. I will only show the double auxiliary stack method which is easy to understand. The core is that in stack 1, the stack order is root left right, and in stack 2, the stack order is root right left
public void noRecursion_post(TreeNode root) { if(root==null) return; Stack<TreeNode> s1 = new Stack<TreeNode>(); Stack<TreeNode> s2 = new Stack<TreeNode>(); TreeNode cur=root; s1.push(cur); while(!s1.isEmpty()){ cur=s1.pop(); s2.push(cur); if (cur.left!=null) s1.push(cur.left); if (cur.right!=null) s1.push(cur.right); } while(!s2.isEmpty()){ System.out.print(s2.pop().val); } }