【递归/迭代】94. Binary Tree Inorder Traversal

二叉树的中序遍历:

/**
 * Definition for a binary tree node.
 * 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) {
        vector<int> ans;
        find(ans,root);
        return ans;
    }
    
    void find(vector<int> &ans,TreeNode *root) //迭代
    {
        stack<TreeNode*> rootTemp;
        TreeNode *p=root;
        while(p!=NULL||rootTemp.size()!=0)
        {
            if(p!=NULL)
            {
                rootTemp.push(p);
                p=p->left;
            }
            else
            {
                p=rootTemp.top();
                rootTemp.pop();
                ans.push_back(p->val);
                p=p->right;
            }
        }
    }
    /*
    void find(vector<int> &ans, TreeNode *root) //递归
    {
        if(root==NULL)
            return;
        
        if(root->left)
            find(ans,root->left);
        ans.push_back(root->val);
        if(root->right)
            find(ans,root->right);
        
    }
    */
};

猜你喜欢

转载自blog.csdn.net/leetcodecl/article/details/80918910