本文整理并介绍二叉树的三种遍历所使用的数据结构和遍历方式。java
题目描述:给定一个二叉树,返回它的 前序 遍历。
递归很简单,要求用非递归实现。web
思路: 栈,遍历时先存放右节点,再存放左节点,可以保证遍历到的是前序序列。算法
public List<Integer> preorderTraversal(TreeNode root) { LinkedList<TreeNode> stack = new LinkedList<>(); List<Integer> list = new ArrayList<>(); if(root == null) return list; stack.addLast(root); while(!stack.isEmpty()){ TreeNode temp = stack.removeLast(); list.add(temp.val); if(temp.right != null){ //栈中先存放右节点 stack.addLast(temp.right); } if(temp.left != null){ //再存放左节点 stack.addLast(temp.left); } } return list; }
题目描述:给定一个二叉树,返回它的中序 遍历。
递归算法很简单,你能够经过迭代算法完成吗?数据结构
思路:栈,依次遍历左节点存放到栈中,而后当前节点非空时弹栈,再遍历右节点。svg
//中序遍历:左根右 public List<Integer> inorderTraversal(TreeNode root){ Stack<TreeNode> stack = new Stack<>(); List<Integer> list = new ArrayList<>(); TreeNode cur = root; //循环结束的标记为cur为空,而且栈为空 while(cur != null || !stack.isEmpty()){ while(cur != null){ stack.add(cur); cur = cur.left; //先遍历左节点 } TreeNode temp = stack.pop();//再操做根节点 list.add(temp.val); cur = temp.right;//再遍历右节点 } return list; }
题目描述:给定一个二叉树,返回它的后序 遍历。
递归算法很简单,你能够经过迭代算法完成吗?
思路: 栈+双向链表(逆向插入)
非递归:栈中先入左节点,后入右节点,弹出时先弹右节点;插入链表后要倒序一遍,能够直接每次都插在最前面
左右根的后序遍历,采用逆向思惟,每次存放都存在最左边
每从栈中弹一个就存到list的最前边
先存根节点,而后左节点入栈,再右节点入栈,弹出时先弹右节点post
/** * 非递归:栈中先入左节点,后入右节点,弹出时先弹右节点;插入链表后要倒序一遍,能够直接每次都插在最前面 * 左右根的后序输出,采用逆向思惟,存放时顺序为根右左,只不过每次存放都存在最左边 * 每从栈中弹一个就存到list的最前边 * 先存根节点,而后左节点入栈,再右节点入栈,弹出时先弹右节点 * */ public List<Integer> postorderTraversal(TreeNode root) { LinkedList<TreeNode> stack = new LinkedList<TreeNode>(); //结果集采用双向链表,在存放值的时候存放在最左边 LinkedList<Integer> output = new LinkedList<>(); if(root == null) return output; stack.push(root); while(!stack.isEmpty()){ TreeNode temp = stack.pop(); output.addFirst(temp.val); //存值到最前边,不用倒序翻转了 if(temp.left != null) stack.push(temp.left); if(temp.right != null) stack.push(temp.right); } return output; }