迭代实现二叉树先序、中序、后序遍历(c++)

树的定义

/**
 * 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> preorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root==NULL) return res;
        stack<TreeNode*> st;
        st.push(root);
        while(!st.empty()){
            TreeNode* top=st.top();
            st.pop();
            res.push_back(top->val);
            if(top->right!=NULL) st.push(top->right);//因为用栈存储,所以先右后左才能先遍历到左子结点
            if(top->left!=NULL) st.push(top->left);
        }
        return res;
    }
};

中序遍历

迭代

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root==NULL) return res;
        stack<TreeNode*> st;
        TreeNode* cur=root;
        while(!st.empty()||cur!=NULL){
            while(cur!=NULL){//找最左侧的结点
                st.push(cur);
                cur=cur->left;
            }
            cur=st.top();
            st.pop();
            res.push_back(cur->val);
            cur=cur->right;
        }
        return res;
    }
};

后序遍历

迭代

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root==NULL) return res;
        stack<TreeNode*> st;
        st.push(root);
        while(!st.empty()){
            TreeNode* top=st.top();
            st.pop();
            res.push_back(top->val);
            if(top->left!=NULL) st.push(top->left);//因为用栈存储,所以先左后右先遍历到右子结点,最终得到后序遍历的逆序列
            if(top->right!=NULL) st.push(top->right);
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

你可能感兴趣的:(LeetCode)