[LeetCode] Binary Tree Inorder Traversal

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

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

 

return [1,3,2].

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

解题思路:

结点的访问顺序是,左子树 -> 自己 -> 右子树。对于一个结点,它可以输出的条件是,其子树已经加入list,同时左子树已经访问完成。这里的实现和后序遍历不同,后序遍历只需要记录最近的访问结点即可。但中序遍历得记录更多。故为每一个结点引入一个状态位。初始加入为0,当它的左右子树都加入时,修改为1(可以输出)。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode *root) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        vector<int> ans;
        list<TreeNode*> node_list;
        list<int> node_state;//0 for not push left and right
        if(root == NULL)
            return ans;
        
        node_list.push_front(root);
        node_state.push_front(0);
        TreeNode *cur = NULL;
        int state = 0;
        
        while(!node_list.empty())
        {
            cur = node_list.front();
            node_list.pop_front();
            state = node_state.front();
            node_state.pop_front();
            
            if(state == 1)
                ans.push_back(cur -> val);
            else
            {
                if(cur -> right != NULL) 
                {
                    node_list.push_front(cur -> right);
                    node_state.push_front(0);
                }
                node_list.push_front(cur);
                node_state.push_front(1);
                if(cur -> left != NULL) 
                {
                    node_list.push_front(cur -> left);
                    node_state.push_front(0);
                }
            }
        }
    }
};

 

posted @ 2013-11-10 19:52  xchangcheng  阅读(159)  评论(0编辑  收藏  举报