[leetcode] 145. Binary Tree Postorder Traversal 두 갈래 트리 뒷면 반복

1496 단어
Given a binary tree, return the postorder traversal of its nodes' values.
For example: Given binary tree {1,#,2,3},
   1
    \
     2
    /
   3

return [3,2,1].
문제 해결 방법:
귀속판:
class Solution {
public:
    void getpostOrderData(TreeNode* root, vector &ret)
    {
        if(!root) return;
        if(root->left) getpostOrderData(root->left,ret);
        if(root->right) getpostOrderData(root->right,ret);
        ret.push_back(root->val);
        return;
    }
    vector postorderTraversal(TreeNode* root) {
        vector ret;
        getpostOrderData(root,ret);
        return ret;
    }
};

교체 버전:
class Solution {
public:
    vector postorderTraversal(TreeNode* root) {
        vector ret;
        stack stk;
        TreeNode* curr = root;
        TreeNode* last = NULL;
        while(curr || !stk.empty())
        {
            while(curr)
            {
                 stk.push(curr);
                 curr = curr->left;
            }
            
            TreeNode* temp = stk.top();
            if(temp->right && last != temp->right )
                curr = temp->right;
            else{
                ret.push_back(temp->val);
                last = temp;
                 stk.pop();
             }
            
        }
        
        return ret;
    }
};

좋은 웹페이지 즐겨찾기