平衡二叉树,即左子树与右子树的最大深度差不大于1.刷到力扣的题,判断该二叉树是否为平衡二叉树,代码如下所示,采用dfs法,进行左右子树深度的一个检验
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null){
return true;
}
return Math.abs(check(root.left)-check(root.right))<=1&&isBalanced(root.left)&&isBalanced(root.right);
}
//求得子树最大深度方法
public int check(TreeNode root){
if(root==null){
return 0;
}
int max1=check(root.left)+1;
int max2=check(root.right)+1;
return Math.max(max1,max2);
}
}
搜索二叉树,父节点的值大于左子树的值,小于右子树的值,中序遍历搜索二叉树,得到的是一串递增的数组,也可用此来判断该树是否为搜索二叉树
搜索二叉树的序列化和反序列化
搜索二叉树的中序遍历是一个升序的数列,有序,为了反序列化,这里使用二叉树的后序遍历,先左子节点,右子节点,最后放父节点,利用栈模拟,成功进行反序列化
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
StringBuilder res=new StringBuilder();
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
houxu(root);
String temp=res.toString();
temp=temp.trim();
return temp;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data.isEmpty()) {
return null;
}
String[] arr = data.split(" ");
Deque<Integer> stack = new ArrayDeque<Integer>();
int length = arr.length;
//序列化的字符串以整型存进栈中
for (int i = 0; i < length; i++) {
stack.push(Integer.parseInt(arr[i]));
}
return construct(Integer.MIN_VALUE, Integer.MAX_VALUE, stack);
}
private TreeNode construct(int lower, int upper, Deque<Integer> stack) {
//存进栈中,吐出来相当于后序遍历的逆序,往外吐
if (stack.isEmpty() || stack.peek() < lower || stack.peek() > upper) {
return null;
}
int val = stack.pop();
TreeNode root = new TreeNode(val);
root.right = construct(val, upper, stack);
root.left = construct(lower, val, stack);
return root;
}
private void houxu(TreeNode root) {
if (root == null) {
return;
}
houxu(root.left);
houxu(root.right);
res = res.append(String.valueOf(root.val));
res.append(" ");
}
}
// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// String tree = ser.serialize(root);
// TreeNode ans = deser.deserialize(tree);
// return ans;