首页 > 解决方案 > 未对齐地址内的成员访问

问题描述

问题链接:https ://leetcode.com/problems/cousins-in-binary-tree

我的代码:

 /**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

class Solution {
public:

bool isCousins(TreeNode* root, int x, int y) {

    //breath first search will be better in this approach
    queue<  pair< TreeNode * , TreeNode *>   > a;
    queue<  pair< TreeNode * , TreeNode *>   > b; // first children..then parent
    a.push({root,NULL});//root-> parent = NULL
    bool check = false;
    auto it = a.front();
    auto it2 = a.front();
    while(a.size() !=0 || b.size() !=0){
        if(a.size() == 0 && b.size() != 0)
            a.swap(b);
        //if(b.size() == 0)
        //    b.push({NULL,NULL});
        it = a.front();
        if(it.first->left != NULL)
            b.push({it.first->left,it.first});
        if(it.first->right != NULL)
            b.push({it.first->right,it.first});
        if( it.first != NULL && (it.first->val == x || it.first->val == y)){
            //we need to find both in this level
            //if not found return false;
            while(a.size() != 0){
                a.pop();
                it2 = a.front();
//this is the line 40
//here....
                    if(it2.first != NULL && (((it2.first)->val == x) || ((it2.first)->val == y))){//all nodes are unique in value
                        if(it2.second == it.second)
                            return false;//same parent ..so not cousin
                        return true;//cousim
                    }    
                }
                //only one of them is found at present depth
                return false;
            }
            if(a.size() !=0)
                a.pop();
        }
        //both not found
        return false;
    }
};

运行时错误:第 40 行:字符 60:运行时错误:在未对齐的地址 0xbebebebebebebebe 内访问类型“TreeNode”的成员,这需要 8 字节对齐 (solution.cpp) 0xbebebebebebebebe:注意:指针指向此处摘要:UndefinedBehaviorSanitizer:未定义行为 prog_joined。 cpp:49:60

标签: stlqueueruntime-errorc++14undefined-behavior

解决方案


推荐阅读