二叉树的遍历(循环方式)
前序遍历(Preorder Traverse)
根结点-左子树-右子树
Java代码实现:
public List<Integer> preorderTraversal(TreeNode root) { List<Integer> ret = new ArrayList<Integer>(); if(root == null) return ret; Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode cur = root; while(cur != null || !stack.isEmpty()){ if(cur != null){ ret.add(cur.val); stack.push(cur); cur = cur.left; }else{ TreeNode node = stack.pop(); cur = node.right; } } return ret; }
后序遍历(postorder traverse)
左子树-右子树-根结点
代码实现:
public List<Integer> postorderTraversal(TreeNode root) { LinkedList<Integer> ret = new LinkedList<Integer>(); if(root == null) return ret; Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode cur = root; while(cur != null || !stack.isEmpty()){ if(cur != null){ stack.push(cur); ret.addFirst(cur.val); cur = cur.right; }else{ TreeNode node = stack.pop(); cur = node.left; } } return ret; }
中序遍历(inorder traverse):
左子树-根结点-右子树
代码实现:
public List<Integer> inorderTraversal(TreeNode root) { List<Integer> ret = new ArrayList<Integer>(); if(root == null) return ret; Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode cur = root; while(!stack.isEmpty() || cur != null){ if(cur != null){ stack.push(cur); cur = cur.left; }else{ TreeNode node = stack.pop(); ret.add(node.val); cur = node.right; } } return ret; }