题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 the root of binary tree * @return int整型二维数组 */ public int[][] threeOrders (TreeNode root) { // write code here List<Integer> list1 = new ArrayList<>(); List<Integer> list2 = new ArrayList<>(); List<Integer> list3 = new ArrayList<>(); //调用函数计算遍历结果 preOrder(root, list1); inOrder(root, list2); postOrder(root, list3); //存放结果集 int[][] res = new int[3][list1.size()]; for (int i = 0; i < list1.size(); i++) { res[0][i] = list1.get(i); res[1][i] = list2.get(i); res[2][i] = list3.get(i); } return res; } private void preOrder(TreeNode root, List<Integer> list) { if(root==null) return; ArrayDeque<TreeNode> stack = new ArrayDeque<>(); stack.push(root); while (!stack.isEmpty()) { TreeNode curr = stack.pop(); list.add(curr.val); if (curr.right != null) { stack.push(curr.right); } if (curr.left != null) { stack.push(curr.left); } } } private void inOrder(TreeNode root, List<Integer> list) { if(root==null) return; ArrayDeque<TreeNode> stack = new ArrayDeque<>(); TreeNode curr = root; while (!stack.isEmpty() || curr != null) { if (curr != null) { stack.push(curr); curr = curr.left; } else { curr = stack.pop(); list.add(curr.val); curr = curr.right; } } } private void postOrder(TreeNode root, List<Integer> list) { if(root==null) return; ArrayDeque<TreeNode> stack = new ArrayDeque<>(); stack.push(root); while (!stack.isEmpty()) { TreeNode curr = stack.pop(); list.add(0,curr.val); if (curr.left != null) { stack.push(curr.left); } if (curr.right != null) { stack.push(curr.right); } } } }