基础题

判断一棵二叉树是否为搜索二叉树和完全二叉树

http://www.nowcoder.com/questionTerminal/f31fc6d3caf24e7f8b4deb5cd9b5fa97

层次遍历判断是否是完全二叉树, 中序遍历判断是否是二叉搜索树

/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 the root
     * @return bool布尔型vector
     */
    long last = -0x3f3f3f3f3f;
    vector<bool> judgeIt(TreeNode* root) {
        // write code here
        bool flag = 1;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            auto p = q.front();
            q.pop();
            if(!q.empty() && p->val == 0x3f3f3f3f && q.front()->val != 0x3f3f3f3f){
                flag = 0;
                break;
            }
            if(p->val != 0x3f3f3f3f) {
                if(p->left) q.push(p->left);
                else q.push(new TreeNode(0x3f3f3f3f));

                if(p->right) q.push(p->right);
                else q.push(new TreeNode(0x3f3f3f3f));
            }
        }
        return {dfs(root), flag};
    }
    bool dfs(TreeNode *root) {
        if(!root) return true;
        bool l = dfs(root->left);
        if(!l || last > root->val) return false;
        last = root->val;
        return dfs(root->right);
    }
};
全部评论

相关推荐

冷艳的小师弟在看机会:jd测评乱点直接被挂了,哭死~
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务