BFS、DFS、先序、中序、后序遍历的非递归算法(java)
一 广度优先遍历(BFS)
//广度优先遍历二叉树,借助队列,queue public static void bfs(TreeNode root){ Queue<TreeNode> queue = new LinkedList<TreeNode>(); //队列需要使用linkedlist来初始化 if(root == null) return; queue.add(root); while(!queue.isEmpty()){ TreeNode node = queue.poll(); System.out.print(node.val + " "); if(node.left != null) queue.add(node.left); if(node.right != null) queue.add(node.right); } }
二 深度优先遍历(DFS)
//深度优先遍历二叉树,借助堆栈,stack public static void dfs(TreeNode root){ Stack<TreeNode> stack = new Stack<TreeNode>(); //借助stack if(root == null) return; stack.push(root); while(!stack.isEmpty()){ //若栈非空 TreeNode node = stack.pop(); System.out.print(node.val + " "); if(node.right != null) //先将右孩子结点压入堆栈 stack.push(node.right); if(node.left != null) //然后将左孩子结点压入堆栈 stack.push(node.left); } }
三、先序遍历非递归(preOrder)
/** * 迭代(即深度优先遍历二叉树) * 先序遍历二叉树 * @param root * @return */ public static List<Object> preorderTraversal(TreeNode root) { List<Object> list = new ArrayList<Object>(); if(root == null) return list; Stack<TreeNode> stack = new Stack<TreeNode>(); stack.add(root); while(!stack.isEmpty()){ TreeNode node = stack.pop(); list.add(node.val); if(node.right != null) //先压入右子树 stack.push(node.right); if(node.left != null) //再压入左子树 stack.push(node.left); } System.out.println(list); return list; }
四、中序遍历非递归(inOrder)
/** * 迭代 * 中序遍历二叉树 * @param root * @return */ public static List<Object> inorderTraversal(TreeNode root) { List<Object> list = new ArrayList<Object>(); if(root == null) return list; Stack<TreeNode> s = new Stack<TreeNode>(); TreeNode p = root; while(p != null || !s.isEmpty()){ while(p != null){ s.push(p); p = p.left; } p = s.pop(); list.add(p.val); p = p.right; } System.out.println(list); return list; }
五、后序遍历非递归(postOrder)
//后序非递归遍历二叉树 public static List<Object> postOrder(TreeNode root){ List<Object> list = new ArrayList<Object>(); if(root == null) return list; Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode node = root, prev = root; //pre记录上一个已经输出的结点 while (node != null || stack.size() > 0) { while (node != null) { stack.push(node); node = node.left; } TreeNode temp = stack.peek().right; //在出栈之前,先判断栈顶元素的右孩子结点 if (temp == null || temp == prev) { //当前节点无右子树或右子树已经输出 node = stack.pop(); list.add(node.val); prev = node; //记录上一个已输出结点 node = null; } else { node = temp; //处理右子树 } } System.out.println(list); return list; }