您当前的位置: 首页 > 

对方正在debug

暂无认证

  • 7浏览

    0关注

    399博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

二叉树的后序遍历(栈实现)

对方正在debug 发布时间:2020-03-03 14:40:52 ,浏览量:7

题目:https://leetcode-cn.com/problems/binary-tree-postorder-traversal/

/**
 * 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 postorderTraversal(TreeNode* root) {
        vector res;
        if(root == nullptr) return res;
        stack st;
        st.push(root);
        while(!st.empty()) {
            TreeNode *cur = st.top();
            st.pop();
            if(cur->left == nullptr && cur->right == nullptr) {
                res.push_back(cur->val);
            }else {
                TreeNode *l = cur->left;
                TreeNode *r = cur->right;
                cur->left = cur->right = nullptr;
                st.push(cur);
                if(r != nullptr) st.push(r);
                if(l != nullptr) st.push(l);
            }
        }
        return res;
    }
};
关注
打赏
1664895754
查看更多评论
立即登录/注册

微信扫码登录

0.0352s