二叉树的5种遍历方式
参考链接:https://blog.csdn.net/u010842515/article/details/68951783
一:前序遍历
递归解法:
public void preOrderTraverse(Node node){ if(node == null) return ; System.out.println(node.data); preOrderTraverse(node.left); preOrderTraverse(node.right); }
非递归解法:
//非递归解法 public void preOrder(Node node){ Stack<Node> stack = new Stack<Node>();if(node == null) return; stack.push(node); while(!stack.empty()){ Node n = stack.pop(); System.out.println(n.data); if(n.right!=null) stack.push(n.right); if(n.left!=null) stack.push(n.left); } listTraverse(list); // return list; } }
二:中序遍历
递归解法:
public void inOrderTraverse(Node node){ if(node == null) return; inOrderTraverse(node.left); System.out.println(node.data); inOrderTraverse(node.right); }
非递归解法:
//非递归 public void inOrder(Node node){ Stack<Node> stack = new Stack<Node>(); while(node!= null || !stack.empty()){ while(node != null){ stack.push(node); node = node.left; } if(!stack.empty()){ node = stack.pop(); System.out.println(node.data); node = node.right; } } }
三:后序遍历
public void postOrderTraverse(Node node){ if(node == null) return; postOrderTraverse(node.left); postOrderTraverse(node.right); System.out.println(node.data); }
四:深度优先遍历
就是前序遍历
五:广度优先遍历
//层次遍历 public void cengOrder(Node node){ if(node == null) return; Queue<Node> queue = new LinkedList<Node>(); queue.add(node); while(!queue.isEmpty()){ Node temp = queue.poll(); System.out.println(temp.data); if(temp.left!=null) queue.add(temp.left); if(temp.right!=null) queue.add(temp.right); } }