[leetcode]Binary Tree Postorder Traversal&&Binary Tree Preorder Traversal

题意:给出了一颗二叉树,求二叉树的前序遍历和后序遍历,题中要求尽量使用非递归方法遍历

后序遍历递归代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void dfs(vector<int> &vec,TreeNode *root)
    {
        if(root->left!=NULL) dfs(vec,root->left);
        if(root->right!=NULL) dfs(vec,root->right);
        vec.push_back(root->val);
    }

vector<int> postorderTraversal(TreeNode *root)
    {
        vector<int> vec;
        if(root!=NULL) dfs(vec,root);
        return vec;
    }
};

非递归代码:

/**
 * 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> postorderTraversal(TreeNode *root)
    {
        vector<int> vec;
        stack<int> num;
        stack<TreeNode*> st;
        if(root!=NULL) st.push(root);
        TreeNode *node;
        while(!st.empty())
            {
                node=st.top();
                st.pop();
                if(node->left!=NULL) st.push(node->left);
                if(node->right!=NULL) st.push(node->right);
                num.push(node->val);
            }
        while(!num.empty())
            {
                vec.push_back(num.top());
                num.pop();
            }
        return vec;
    }
};

先序遍历递归代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void dfs(vector<int> &vec,TreeNode *root)
    {
        vec.push_back(root->val);
        if(root->left!=NULL) dfs(vec,root->left);
        if(root->right!=NULL) dfs(vec,root->right);
    }

vector<int> preorderTraversal(TreeNode *root)
    {
        vector<int> vec;
        if(root!=NULL) dfs(vec,root);
        return vec;
    }
};

先序遍历非递归代码:
/**
 * 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> preorderTraversal(TreeNode *root)
    {
        vector<int> vec;
        stack<TreeNode*> st;
        TreeNode *node;
        while(root||!st.empty())
            {
                while(root)
                    {
                        st.push(root);
                        vec.push_back(root->val);
                        root=root->left;
                    }
                root=st.top();
                st.pop();
                root=root->right;
            }
        return vec;
    }
};

你可能感兴趣的:(LeetCode,遍历,二叉树)