LeetCode 145 Binary Tree Postorder Traversal(二叉树的后续遍历)+(二叉树、迭代)

版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50933610

翻译

给定一个二叉树,返回其后续遍历的节点的值。

例如:
给定二叉树为 {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(二叉树的前序遍历)+(二叉树、迭代)

上一篇:二叉树的层序遍历和二叉树的线索化


下一篇:自己动手丰衣足食之纯CSS画的基本图形(矩形、圆形、三角形、多边形、爱心、八卦等)