二叉树遍历:
前序遍历:根节点->左儿子->右儿子
中序遍历:左儿子->根节点->右儿子
后序遍历:左儿子->右儿子->根节点
例如给定一个树A
前序遍历:[1,2,4,5,3,6]
中序遍历:[4,2,5,1,6,3]
后序遍历:[4,5,2,6,3,1]
定义节点:
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; } }
六种遍历方式:
public class Solution { //递归遍历 //前序遍历 public void recurPreOrder(TreeNode node){ if(node == null) return; System.out.print(node.val+" "); recurPreOrder(node.left); recurPreOrder(node.right); } //中序遍历 public void recurInOrder(TreeNode node){ if(node == null) return; recurInOrder(node.left); System.out.print(node.val+" "); recurInOrder(node.right); } //后序遍历 public void recurPostOrder(TreeNode node){ if(node == null) return; recurPostOrder(node.left); recurPostOrder(node.right); System.out.print(node.val+" "); } //非递归遍历 //前序遍历 public void PreOrder(TreeNode node){ LinkedList<TreeNode> list = new LinkedList<>();//LinkedList模拟栈的先进后出 while(node!=null||!list.isEmpty()){ while(node!=null){ list.addFirst(node); System.out.print(node.val +" "); node = node.left;//遍历左子树 } node = list.removeFirst(); node = node.right;//出栈一个节点,找到其右儿子,返回上面的循环继续遍历右儿子的左子树 } } //中序遍历 public void InOrder(TreeNode node){ LinkedList<TreeNode> list = new LinkedList<>(); while(node!=null || !list.isEmpty()){ while(node!=null){ list.addFirst(node); node = node.left; } node = list.removeFirst(); System.out.print(node.val+" "); node = node.right; } } //后序遍历 public void PostOrder(TreeNode node){ LinkedList<TreeNode> list = new LinkedList<>(); LinkedList<TreeNode> tempList = new LinkedList<>();//临时栈 while(node!=null || !tempList.isEmpty()){ while(node!=null){ tempList.addFirst(node); list.addFirst(node); node = node.right;//后序遍历相当于前序遍历的逆序,所以先遍历右子树把节点存入两个栈 } if(!tempList.isEmpty()){//当右子树没有右儿子时候,栈顶出栈,遍历左子树 node = tempList.removeFirst(); node = node.left; } } while(!list.isEmpty()){ System.out.print(list.removeFirst().val+" "); } } }
测试:
@Test public void testTree(){ TreeNode node6 = new TreeNode(6,null,null); TreeNode node5 = new TreeNode(5,null,null); TreeNode node4 = new TreeNode(4,null,null); TreeNode node3 = new TreeNode(3,node6,null); TreeNode node2 = new TreeNode(2,node4,node5); TreeNode node1 = new TreeNode(1,node2,node3); //先序遍历 System.out.println("先序遍历"); recurPreOrder(node1); System.out.println(); PreOrder(node1); System.out.println(); //中序遍历 System.out.println("中序遍历"); recurInOrder(node1); System.out.println(); InOrder(node1); System.out.println(); //后序遍历 System.out.println("后序遍历"); recurPostOrder(node1); System.out.println(); PostOrder(node1); System.out.println(); }