首页 > ”二叉树之的之字形层遍历“的段错误
头像
憨憨牛牛勇敢冲
编辑于 2021-01-17 12:33
+ 关注

”二叉树之的之字形层遍历“的段错误

在解决NC14,"二叉树之的之字形层遍历"这一问题时,使用两个栈代替队列进行存储过程节点,但是自测的时候,可以显示正确的答案,提交后显示“段错误”,通过样例为0,
请问代码如下,恳请大佬帮我看一下。
/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @return int整型vector<vector<>>
     */
    // 在实现上使用两个栈,
    vector<vector<int> > zigzagLevelOrder(TreeNode* root) {
        // write code here
        stack<TreeNode*> left, right;
        vector<vector<int>> result;
        TreeNode *p;
        p = root;
        left.push(root);
        while(!left.empty() || !right.empty())
        {
            vector<int> temp;
            if(!left.empty())
            {
                while(!left.empty())
                {
                    p = left.top(); left.pop();
                    temp.push_back(p->val);
                    if(p->left)
                        right.push(p->left);
                    if(p->right)
                        right.push(p->right);
                }
                result.push_back(temp);
            }
            else
            {
                while(!right.empty())
                {
                    p = right.top(); right.pop();
                    temp.push_back(p->val);
                    if(p->right)
                        left.push(p->right);
                    if(p->left)
                        left.push(p->left);
                }
                result.push_back(temp);
            }
        }
        return result;
    }
};

全部评论

(0) 回帖
加载中...
话题 回帖

推荐话题

相关热帖

近期精华帖

热门推荐