LeetCode 145 Binary Tree Postorder Traversal(두 갈래 나무의 후속 반복)+(두 갈래 나무, 교체)

번역하다

 , 。

 :
  {1#, 2, 3}
   1
    \
     2
    /
   3
  [3, 2, 1]

 : , ?

원문

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].

Note: Recursive solution is trivial, could you do it iteratively?

분석


코드를 바로...
vector<int> postorderTraversal(TreeNode* root) {
    if (root != NULL) {
        postorderTraversal(root->left);
        postorderTraversal(root->right);     
        v.push_back(root->val);
    }
    return v;
}
/** * 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> v;

    void  postorderTraversalIter(TreeNode *root, stack<TreeNode*> &stac) {
        if (root == NULL) return;
        bool hasLeft = root->left != NULL;
        bool hasRight = root->right != NULL;
        stac.push(root);
        if (hasRight)
            stac.push(root->right);
        if (hasLeft)
            stac.push(root->left);
        if (!hasLeft && !hasRight)
            v.push_back(root->val);
        if (hasLeft) {
            root = stac.top();
            stac.pop();
            postorderTraversalIter(root, stac);
        }
        if (hasRight) {
            root = stac.top();
            stac.pop();
            postorderTraversalIter(root, stac);
        }
        if (hasLeft || hasRight)
            v.push_back(stac.top()->val);
        stac.pop();
    }

    vector<int> postorderTraversal(TreeNode* root) {
        stack<TreeNode*> stac;
        postorderTraversalIter(root, stac);
        return v;
    }     
};

또 다른 두 가지 유사한 제목이 있다.
LeetCode 94 Binary Tree Inorder Traversal(두 갈래 나무의 중차 범람)+(두 갈래 나무, 교체)LeetCode 144 Binary Tree Preorder Traversal(두 갈래 나무의 전차 범람)+(두 갈래 나무, 교체)

좋은 웹페이지 즐겨찾기