Niuke.com, 이진 트리가 완전한 이진 트리 및 BST인지 확인

제목 설명

여기에 사진 설명 삽입

해결책:

BST를 판단하려면 min <current node <max가 필요하며 왼쪽 및 오른쪽 하위 트리도 유사한 규칙을 충족합니다.
완전한 이진 트리를 판단하려면 노드가 하나 인 한 레이어에 따라 판단해야합니다.

if(cur.left==null && cur.right!=null) return false;

완전한 이진 트리가 아닙니다.
코드 참조 :

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    
    
    /**
     * 
     * @param root TreeNode类 the root
     * @return bool布尔型一维数组
     */
    public boolean[] judgeIt (TreeNode root) {
    
    
        
        // write code here
        boolean[]res = new boolean[2];
        if(root==null) {
    
    
            res[0] = true;
            res[1] = true;
            return res;
        }
        res[0] = isBST(root,Integer.MAX_VALUE,Integer.MIN_VALUE);
        res[1] = isBinaryTree(root);
        return res;
    }
    //判断BST二叉树,使用一个max和min来限制范围:
    //当前节点必须满足: max>=root>=min
    public boolean isBST(TreeNode root,int max,int min){
    
    
        if(root== null) return true;
        if(root.val>=max || root.val<=min){
    
    
            return false;
        }
        
        boolean leftRes = isBST(root.left,root.val,min);
        boolean rightRes = isBST(root.right,max,root.val);
        return leftRes && rightRes;
        
    }
    public boolean isBinaryTree(TreeNode root){
    
    
        if(root==null) return true;
        //完全二叉树的标号同满二叉树的标号则相同。
        //按照层级遍历的序号,如果得到的数据和满二叉树的节点值一致则为true
        int fullId = 0;//满二叉树的id
        int judgeId = 0;//完全二叉树的id
        LinkedList<TreeNode> que = new LinkedList<>();
        que.add(root);
        while(!que.isEmpty()){
    
    
            int size = que.size();
            for(int i=0;i<size;i++){
    
    //当前层的节点
                TreeNode cur = que.remove();
                if(cur!=null){
    
    
                    if(cur.left==null && cur.right!=null) return false;
                    
                    que.add(cur.left);
                    que.add(cur.right);
                }else continue;
               
                
            }
       }
        return true; 
    }
}

여기에 사진 설명 삽입

추천

출처blog.csdn.net/qq_44861675/article/details/114927275