二叉树练习
1、二叉树按层遍历并收集节点
Leetcode原题,https://leetcode.com/problems/binary-tree-level-order-traversal-ii
public static List fangfa(Node root){
LinkedList<LinkedList<Integer>> linkedLists = new LinkedList<>();
if (root == null) return linkedLists;
Queue queue = new LinkedList();
queue.add(root);
while (!queue.isEmpty()){
LinkedList list = new LinkedList();
int size = queue.size();
for (int i = 0; i < size; i++){
Node p = (Node) queue.poll();
list.add(p.value);
if (p.left!=null) queue.add(p.left);
if (p.right!=null) queue.add(p.right);
}
linkedLists.add(0, list);
}
return linkedLists;
}
2、判断是否是平衡搜索二叉树
Leetcode原题,https://leetcode.com/problems/balanced-binary-tree
用第二个类来记录
public static class Info{
boolean balance;
int height;
public Info(){
}
public Info(boolean balance, int height){
this.balance = balance;
this.height = height;
}
}
public static Info isBalance(Node root){
if (root == null){
return new Info(true, 0);
}
Info ifo = new Info();
ifo.height = Math.max(isBalance(root.left).height, isBalance(root.right).height)+1;
ifo.balance = Math.abs(isBalance(root.left).height - isBalance(root.right).height)<2;
return ifo;
}
3、判断二叉树是否是搜索二叉树
public static Info sousuoerchashu(Node root){
if (root == null) return null;
Info ssh = new Info();
Info ss1 = sousuoerchashu(root.left);
Info ss2 = sousuoerchashu(root.right);
if (ss1 != null && ss2 != null){
ssh.min = ss1.max;
ssh.max = ss2.min;
if (ssh.min < root.value && ssh.max > root.value){
ssh.sousuo = true;
}else ssh.sousuo = false;
}
else if (ss1 == null && ss2 != null){
ssh.max = ss2.min;
ssh.min = root.value;
if (root.value < ss2.min){
ssh.sousuo = true;
}else ssh.sousuo = false;
}
else if (ss1 != null && ss2 == null){
ssh.min = ss1.max;
ssh.max = root.value;
if (root.value > ss1.max){
ssh.sousuo = true;
}else ssh.sousuo = false;
}else {
ssh.min = root.value;
ssh.max = root.value;
ssh.sousuo = true;
}
return ssh;
}
public static class Info{
boolean sousuo;
int min;
int max;
public Info(){
}
public Info(boolean sousuo){
this.sousuo = sousuo;
}
public Info(int min, int max){
this.min = min;
this.max = max;
}
}
4、在二叉树上能否组成路径和
Leetcode原题,https://leetcode.com/problems/path-sum
public static boolean f(Node head, int preSum, int sum){
if (head == null && preSum == sum) return true;
else if (head == null && preSum != sum) return false;
else if (head != null && preSum == sum) return false;
else {
if (f(head.left, preSum+head.value, sum)) return true;
if (f(head.right, preSum+head.value, sum)) return true;
else return false;
}
}
5、在二叉树上收集所有达标的路径和
注意集合的复制!!!!
public static void f2(Node head, int preSum, int sum, List list, List<List> lists){
if (head.left == null && head.right == null){
if (preSum+head.value == sum){
list.add(head.value);
lists.add(copy1(list));
list.remove(list.size()-1);
}
return;
}
preSum+=head.value;
list.add(head.value);
if (head.left!=null){
f2(head.left, preSum, sum, list, lists);
}
if (head.right!=null){
f2(head.right, preSum, sum, list, lists);
}
list.remove(list.size()-1);
return;
}