94. Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.

For example:
Given binary tree [1,null,2,3],

   1
    \
     2
    /
   3

 

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

本题要求用迭代来做,如果用迭代来解决,就必须使用stack来解决,里面用来存储下一个需要遍历的node,思路是,创建一个stack和TreeNode,让treenode指向当前的节点,先遍历到最左面的节点,将其值存放在list里面,然后遍历该节点右节点,进入下一步循环(值得注意的是,最左面的节点也可以当作是该节点为中节点),代码如下:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<Integer> inorderTraversal(TreeNode root) {
12         List<Integer> res = new ArrayList<Integer>();
13         Stack<TreeNode> stack = new Stack<TreeNode>();
14         TreeNode cur = root;
15         while(cur!=null||!stack.isEmpty()){
16             while(cur!=null){
17                 stack.push(cur);
18                 cur = cur.left;
19             }
20             cur = stack.pop();
21             res.add(cur.val);
22             cur = cur.right;
23         }
24         return res;
25     }
26 }

 

posted @ 2017-03-23 06:06  CodesKiller  阅读(130)  评论(0编辑  收藏  举报