Problem Description
Given a binary tree, there are no nodes with duplicate values in it, please judge whether the binary tree is a search binary tree or a complete binary tree .
Enter description:
Enter a tree
Output description:
output an array of bool type, whether the first one is a binary search tree, and whether the second one is a complete binary tree
Example
Example 1
Enter
{2,1,3}
Output
[true,true]
Solutions
analysis
-
Judgment of binary search tree:
- Wrong idea: It is impossible to judge whether each subtree meets the conditions of the binary search tree by recursively
3 / \ 2 5 / \ 1 4
- The correct idea: by limiting the maximum value of the left subtree and the minimum value of the right subtree to determine, only need to traverse the node once
-
Judgment of a complete binary tree
- Property: The depth of a complete binary tree with n nodes is log2n + 1
- Judge whether it is a complete binary tree by judging the height of the tree, the maximum depth difference between the left subtree and the right subtree does not exceed 1
method
- Binary search tree: through recursion, pass in the limited minimum and maximum values to determine whether it conforms to the nature of the binary search tree
- Complete binary tree: by calculating the maximum height of the left subtree and the right subtree, the left contrast difference, the difference is greater than 1, then it is not
Code
public class Solution {
/**
* @param root TreeNode类 the root
* @return bool布尔型一维数组
*/
public boolean[] judgeIt (TreeNode root) {
// write code here
boolean[] result = new boolean[]{
false, false};
result[0] = isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
result[1] = isBalance(root);
return result;
}
// 错误思路:判断是否是二叉搜索树
// 3
// / \
// 2 5
// / \
// 1 4
private boolean isBinarySearch (TreeNode root) {
if (root == null) {
return true;
}
int val = root.val;
if (root.left != null && val < root.left.val) {
return false;
}
if (root.right != null && val > root.right.val) {
return false;
}
return isBinarySearch(root.left) & isBinarySearch(root.right);
}
// 通过限定每个子节点的范围
private boolean isBST(TreeNode root, int min, int max) {
if(root == null)
return true;
if(root.val < min || root.val > max)
return false;
// 左节点要求小于根节点的值,最大值发挥作用;右节点要求大约根节点的值,最小值发挥作用
return isBST(root.left, min, root.val - 1) && isBST(root.right, root.val + 1, max);
}
// 判断是否是完全二叉树
private boolean isBalance(TreeNode root) {
boolean[] res = new boolean[1];
res[0] = true;
getHeight(root, res);
return res[0];
}
private int getHeight(TreeNode root, boolean[] i) {
if (i[0] == false) {
return 0;
}
if (root == null) {
return 0;
}
// 判断左右节点的高度
int l = getHeight(root.left, i) + 1;
int r = getHeight(root.right, i) + 1;
if (Math.abs(r - l) > 1) {
i[0] = false;
}
return Math.max(l, r);
}
}
If you want to test, you can go directly to the link of Niuke.com to do the test
Determine whether a binary tree is a search binary tree or a complete binary tree-牛客网