[Daily question] 32: Post-order traversal of binary tree

Title description

Given a binary tree, return its postorder traversal.

Example:

输入: [1,null,2,3]  
   1
    \
    2
    /
   3 

输出: [3,2,1]

Advanced: The recursive algorithm is very simple, can you complete iterative algorithm?

Recursive algorithm

Answer code

/**
 * 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 {
    vector<int> v;
public:
    vector<int> postorderTraversal(TreeNode* root) {
        if(root){
            postorderTraversal(root -> left);
            postorderTraversal(root -> right);
            v.push_back(root->val);
        }
        
        return v;
    }
};

Non-recursive algorithm

Answer code

class Solution {
    vector<int> v;
    vector<int> tag;
    stack<TreeNode*> m_st;
public:
    vector<int> postorderTraversal(TreeNode* root) {
        if (root == nullptr) 
            return v;

        TreeNode* cur = root;
        do{
            for (; cur; cur = cur->left) {
                m_st.push(cur);
                tag.push_back(0);
            }
			
			//两个判断条件不能写反(当tag为空数组时会越界)
            while (!m_st.empty() && tag[tag.size() - 1]) {
                cur = m_st.top();
                v.push_back(cur->val);
                m_st.pop();
                tag.pop_back();
            }

            if (!m_st.empty()) {
                cur = m_st.top();
                tag[tag.size() - 1] = 1;
                cur = cur->right;
            }
        }while(!m_st.empty());

        return v;
    }
};

If you have different opinions, please leave a message to discuss

Published 152 original articles · praised 45 · 10,000+ views

Guess you like

Origin blog.csdn.net/AngelDg/article/details/105395831