LeetCode Same Tree(非递归)

2018-04-13  本文已影响0人  codingcyx

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

bool isSameTree(TreeNode* p, TreeNode* q) {
        queue<TreeNode*> que;
        que.push(p);
        que.push(q);
        while(!que.empty()){
            p = que.front();
            que.pop();
            q = que.front();
            que.pop();
            if(!p && !q)
                continue;
            if(!p || !q || (p -> val != q -> val))
                return false;
            que.push(p -> left);
            que.push(q -> left);
            que.push(p -> right);
            que.push(q -> right);
        }
        return true;
    }
上一篇 下一篇

猜你喜欢

热点阅读