题解 | #判断一棵二叉树是否为搜索二叉树和完全二叉树#

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

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

中序遍历+层序遍历

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

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 the root
     * @return bool布尔型vector
     */
    bool isFirst = true;
    bool isSearchTree = true;
    int pre;
    void inOrder(TreeNode* root){
        if(root == NULL) return;
        inOrder(root -> left);
        if(isFirst){
            pre = root -> val;
            isFirst = false;
        }else{
            if(pre >= root -> val){
                isSearchTree = false;
                return;
            }
            pre = root -> val;
        }
        inOrder(root -> right);
    }
    bool isCompTree(TreeNode* root){
        if(root == NULL) return true;
        queue<TreeNode*> q;
        q.push(root);
        int size = 0;
        while(!q.empty()){ //一旦遇到NULL,则后面不能有非空节点
            TreeNode* node = q.front(); q.pop();
            if(node == NULL) break;
            q.push(node -> left);
            q.push(node -> right);
        }
        while(!q.empty() && q.front() == NULL){
            q.pop();
        }
        return q.empty();
    }
    vector<bool> judgeIt(TreeNode* root) {
        // write code here
        inOrder(root);
        return {isSearchTree, isCompTree(root)};
    }
};
全部评论

相关推荐

一颗宏心:华为HR晚上过了十二点后还给我法消息。
点赞 评论 收藏
分享
牛客279957775号:铁暗恋
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务