LeetCode:二叉树的中序遍历(递归与非递归法)

二叉树结点类:

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x): val(x), left(NULL), right(NULL) {}
};

递归法: 

class Solution{

public:

    void inOrder(TreeNode *root, vector &vec)
    {
        if(root != NULL)
        {
            inOrder(root->left, vec);

            vec.push_back(root->val);
            
            inOrder(root->right, vec);        
        }
    }

    vector inorderTraversal(TreeNode *root)
    {
        vector vec;
        inOrder(root, vec);
        return vec;
    }

非递归法:

借助栈来实现中序遍历(左根右):

代码1:

class Solution {
public:
    vector inorderTraversal(TreeNode *root) {
        vector res;
        if(root == NULL)
            return res;
        stack st;

        TreeNode *p = root;

        while(p || st.size())
        {
            if(p)
            {
                st.push(p);
                p = p->left;
            }
            else
            {
                 p = st.top();
                 st.pop();
                 res.push_back(p);
                 p = p->right;  
            }
        }        

        return res;
    }
};

代码2:

class Solution {
public:
    vector inorderTraversal(TreeNode *root) {
        vector res;
        if(root == NULL)
            return res;
        stack st;

        TreeNode *p = root;
        while(p || st.size())
        {
            while(p)
            {
                st.push(p);
                p = p->left;
            }
            if(st.size())
            {
                 p = st.top();
                 st.pop();
                 res.push_back(p);
                 p = p->right;  
            }
        }        

        return res;
    }
};

代码3:(有待验证)

class Solution {
public:
    vector inorderTraversal(TreeNode *root) {
        vector res;
        if(root == NULL)
            return res;
        stack st;

        TreeNode *p = root;
        st.push(p);
        while(p || st.size())
        {
            while(p->left)
            {
                p = p->left;
                st.push(p);
            }
            if(st.size())
            {
                 p = st.top();
                 st.pop();
                 res.push_back(p);
                 p = p->right;  
            }
        }        

        return res;
    }
};

 

你可能感兴趣的:(C/C++,LeetCode)