非递归遍历二叉树

三种非递归遍历的方法

非递归前序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        stack<TreeNode*> st;
        vector<int> ans;
        if(!root) return ans;
        st.push(root);
        while(st.size()) {
            TreeNode* h = st.top();
            st.pop();
            ans.emplace_back(h->val);
            if(h->right) st.push(h->right);
            if(h->left) st.push(h->left);
        }
        return ans;
    }
};

非递归中序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        stack<TreeNode*> st;
        vector<int> ans;
        if(!root) return ans;
        while(!st.empty() || root){
            if(root) { 
                st.push(root);
                root = root->left;
            }else {
                root = st.top();
                st.pop();
                ans.push_back(root->val);
                root = root->right;
            }
        }
        return ans;
    }
};

非递归后续遍历


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> ans;
        if(root == nullptr) return {};
        stack<TreeNode*> st;
        
        st.push(root);
        TreeNode* h, *p;
        h = root, p = root;
        // p 代表上次被打印的root,初始化为非null
        while(st.size()) {
            h = st.top();
            // 判断打印节点是否为子节点,由此判断该根节点是否应该被打印
            if(h->left && h->left != p && h->right != p) st.push(h->left);
            else if(h->right && h->right != p) st.push(h->right);
            else {
                ans.push_back(h->val);
                st.pop();
                p = h;
            }

        }
        return ans;
    }

};

Comments