题目大意:返回二叉树的先序遍历list。中序见94,后序见145。
法一:普通递归遍历,只是这里多了一个list数组,所以分成了两个函数。代码如下(耗时1ms):
1 public List<Integer> preorderTraversal(TreeNode root) { 2 List<Integer> list = new ArrayList<Integer>(); 3 list = dfs(root, list); 4 return list; 5 } 6 public static List<Integer> dfs(TreeNode root, List<Integer> list) { 7 if(root == null) { 8 return list; 9 } 10 else { 11 list.add(root.val); 12 list = dfs(root.left, list); 13 list = dfs(root.right, list); 14 return list; 15 } 16 }
法二(借鉴):先序非递归。代码如下(耗时1ms):
1 public List<Integer> preorderTraversal(TreeNode root) { 2 Stack<TreeNode> stack = new Stack<TreeNode>(); 3 TreeNode tmp = root; 4 List<Integer> list = new ArrayList<Integer>(); 5 while(tmp != null || !stack.isEmpty()) { 6 //将所有左孩子压栈,直到没有左孩子,并且由于是先序遍历,所以在压左孩子的时候就放入结果list中 7 while(tmp != null) { 8 list.add(tmp.val); 9 stack.push(tmp); 10 tmp = tmp.left; 11 } 12 //如果左孩子压完了,就访问右孩子 13 if(!stack.isEmpty()) { 14 tmp = stack.pop(); 15 tmp = tmp.right; 16 } 17 } 18 return list; 19 }
中序非递归:
1 public List<Integer> inorderTraversal(TreeNode root) { 2 List<Integer> list = new ArrayList<Integer>(); 3 Stack<TreeNode> stack = new Stack<TreeNode>(); 4 TreeNode tmp = root; 5 while(tmp != null || !stack.isEmpty()) { 6 while(tmp != null) { 7 stack.push(tmp); 8 tmp = tmp.left; 9 } 10 //与先序不同的是,在弹出时放入结果list 11 if(!stack.isEmpty()) { 12 tmp = stack.pop(); 13 list.add(tmp.val); 14 tmp = tmp.right; 15 } 16 } 17 return list; 18 }