二叉树三序迭代遍历(Java)
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/questionTerminal/a9fec6c46a684ad5a3abd4e365a9d362
public class Solution { /** * * @param root TreeNode类 the root of binary tree * @return int整型二维数组 */ public int[][] threeOrders (TreeNode root) { // write code here int[][] res = new int[3][]; res[0] = toIntArray(preorder(root)); res[1] = toIntArray(inorder(root)); res[2] = toIntArray(postorder(root)); return res; } //将List转换为整型数组 int[] toIntArray(List<Integer> list){ int[] res = list.stream().mapToInt(Integer::intValue).toArray(); return res; } //preorder List<Integer> preorder(TreeNode root) { List<Integer> res = new ArrayList<>(); Stack<TreeNode> stk = new Stack<>(); TreeNode cur = root; while(cur != null || !stk.isEmpty()){ while(cur != null){ res.add(cur.val); stk.push(cur); cur = cur.left; } cur = stk.pop(); cur = cur.right; } return res; } //inorder List<Integer> inorder(TreeNode root) { List<Integer> res = new ArrayList<>(); Stack<TreeNode> stk = new Stack<>(); TreeNode cur = root; while(cur != null || !stk.isEmpty()){ while(cur != null){ stk.push(cur); cur = cur.left; } cur = stk.pop(); res.add(cur.val); cur = cur.right; } return res; } //postorder List<Integer> postorder(TreeNode root) { List<Integer> res = new ArrayList<>(); Stack<TreeNode> stk = new Stack<>(); TreeNode cur = root; while(cur != null || !stk.isEmpty()){ while(cur != null){ res.add(0, cur.val); stk.push(cur); cur = cur.right; } cur = stk.pop(); cur = cur.left; } return res; } }