递归套路,主要是分解信息和合并左右子树需要提供的信息。
当前节点是完全二叉树条件:左子树为完全二叉树 右子树也为完全二叉树 且 左树为空时右树必须为空
当前节点是二叉搜索树条件:左右子树都为搜索树 且 左树根节点值及其根节点右节点都小于当前节点。右树同理
上代码:
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 if(root==null){ return new boolean[]{false,false}; } Info result=judgeItInfo(root); return new boolean[]{result.isSearch,result.isAll}; } class Info{ boolean isSearch; boolean isAll; Integer val; Integer leftVal; Integer rightVal; Info(boolean isSearch,boolean isAll,Integer val,Integer leftVal,Integer rightVal){ this.isSearch=isSearch; this.isAll=isAll; this.val=val; this.leftVal=leftVal; this.rightVal=rightVal; } } public Info judgeItInfo(TreeNode root){ if(root==null){ return new Info(true,true,null,null,null); } Info leftInfo=judgeItInfo(root.left); Info rightInfo=judgeItInfo(root.right); boolean isSearch=leftInfo.isSearch&&rightInfo.isSearch; boolean isAll=leftInfo.isAll&&rightInfo.isAll; //左节点为空 右节点不为空 则不是完全二叉树 if(leftInfo.val==null&&rightInfo.val!=null){ isAll=false; } //判断是否为搜索树时注意 左右子树的左右子树也需要跟根节点比较 if(leftInfo.val!=null){ isSearch=isSearch&&leftInfo.val<=root.val; if(leftInfo.rightVal!=null){ isSearch=isSearch&&leftInfo.rightVal<=root.val; } } if(rightInfo.val!=null){ isSearch=isSearch&&rightInfo.val>=root.val; if(rightInfo.leftVal!=null){ isSearch=isSearch&&rightInfo.leftVal>=root.val; } } return new Info(isSearch,isAll,root.val,root.left==null?null:root.left.val,root.right==null?null:root.right.val); } }