94.Binary Tree Inorder Traversal---二叉树中序非递归遍历
题目大意:中序遍历二叉树。先序见144,后序见145。
法一:DFS,没啥说的,就是模板DFS。代码如下(耗时1ms):
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public List<Integer> inorderTraversal(TreeNode root) { 2 List<Integer> res = new ArrayList<Integer>(); 3 dfs(res, root); 4 return res; 5 } 6 private void dfs(List<Integer> res, TreeNode root) { 7 if(root != null) { 8 dfs(res, root.left); 9 res.add(root.val); 10 dfs(res, root.right); 11 } 12 }
法二:非递归。与先序类似。代码如下(耗时2ms):
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public List<Integer> inorderTraversal(TreeNode root) { 2 Stack<TreeNode> s = new Stack<TreeNode>(); 3 List<Integer> res = new ArrayList<Integer>(); 4 TreeNode tmp = root; 5 while(!s.isEmpty() || tmp != null) { 6 //压入左孩子结点 7 while(tmp != null) { 8 s.push(tmp); 9 tmp = tmp.left; 10 } 11 //如果栈非空,弹出顶结点,遍历右子树 12 if(!s.isEmpty()) { 13 tmp = s.pop(); 14 res.add(tmp.val); 15 tmp = tmp.right; 16 } 17 } 18 return res; 19 }