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

递归:

class Solution {
public:
    vector<int> v;
    vector<int> inorderTraversal(TreeNode* root) {
          if(root!=NULL){
            inorderTraversal(root->left);
              v.push_back(root->val);
            inorderTraversal(root->right);
        }
        return v;
    }
};
非递归实现:
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int>v;
        stack<TreeNode*> s;
        map<TreeNode*,bool>visit;
        if(root!=NULL)s.push(root);
        while(!s.empty()){
            TreeNode *t=s.top();
            if(!visit[t]&&t->left){
                s.push(t->left);
                visit[t]=true;
            }else{
                v.push_back(t->val);
                s.pop();
                if(t->right)
                    s.push(t->right);
            }
        }
        return v;
    }
};


你可能感兴趣的:(94. Binary Tree Inorder Traversal)