0二叉樹中等 牛客NC60.判斷一顆二叉樹是否為搜尋二叉樹和完全二叉樹
阿新 • • 發佈:2020-12-31
題目描述
給定一棵二叉樹,已經其中沒有重複值的節點,請判斷該二叉樹是否為搜尋二叉樹和完全二叉樹。
思路
判斷搜尋二叉樹 :
建立一個全域性變數儲存當前結點的前一個結點,中序遍歷二叉樹判斷當前結點的數值是否比前一個結點大。
也可以中序遍歷數將遍歷到的結點儲存在一個集合中,檢查是否遞增。
判斷完全二叉:
橫向遍歷樹,當第一次遇到一個節點為空,則這個節點後面的節點也必須全部為空。
import java.util.*;
public class Solution {
public boolean[] judgeIt ( TreeNode root) {
boolean[] res = new boolean[]{false,false};
if(root == null){
return res;
}
res[0] = search(root);
res[1] = complete(root);
return res;
}
Integer pre = Integer.MIN_VALUE;
public boolean search(TreeNode root){
if (root == null){
return true;
}
boolean a = search(root.left);
if(root.val <= pre){
return false;
}else{
pre = root.val;
}
boolean b = search(root.right);
return a && b;
}
public boolean complete(TreeNode root){
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
TreeNode temp = queue.poll();
if(temp == null){
while(!queue.isEmpty()){
TreeNode tn = queue.poll();
if(tn != null){
return false;
}
}
break;
}
queue.offer(temp.left);
queue.offer(temp.right);
}
return true;
}
}