LeetCode--Binary Tree Inorder Traversal

题目:

Given 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].

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> vec;
        stack<TreeNode*> stk;
        while(root != NULL || !stk.empty())
        {
            while(root)  //获取最左节点,并将沿路节点入栈
            {
                stk.push(root);
                root = root->left;
            }
            root = stk.top();
            vec.push_back(root->val);
            stk.pop();
            root = root->right;
        }
        return vec;
    }



posted on 2015-11-03 14:40  小二杰  阅读(97)  评论(0编辑  收藏  举报

导航