package www.yide.leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* @ Author :mask
* @ Date :Created in 下午4:07 20-11-14
* @ Description:${description}
* @ Modified By:
* @Version: $version$
*/
public class BalanceBinaryTree {
public static void main(String[] args) {
//创建一颗树
List<TreeNode> treeNodes = new ArrayList<>(100);
TreeNode treeNode1 = new TreeNode();
treeNode1.val = 0;
treeNode1.left = null;
treeNode1.right = null;
TreeNode treeNode2 = new TreeNode();
treeNode2.val = 0;
treeNode2.left = null;
treeNode2.right = treeNode1;
TreeNode treeNode3 = new TreeNode();
treeNode3.val = 0;
treeNode3.left = null;
treeNode3.right = null;
TreeNode treeNode4 = new TreeNode();
treeNode4.val = 0;
treeNode4.left = treeNode2;
treeNode4.right = treeNode3;
TreeNode treeNode5 = new TreeNode();
treeNode5.val = 0;
treeNode5.left = treeNode4;
treeNode5.right = null;
BalanceBinaryTree balanceBinaryTree = new BalanceBinaryTree();
balanceBinaryTree.calculateNodeDeep(treeNode5);
// 使用先序遍验证统计的子树的深度是否正确
balanceBinaryTree.preOder(treeNode5);
int isTrue = 1;
balanceBinaryTree.isBalanceBinaryTree(treeNode5,isTrue);
if (isTrue == 0){
System.out.println("false");
}
}
/**
* 递归i计算节点的深度
*
* @param root
* @return
*/
public void calculateNodeDeep(TreeNode root) {
// 叶子节点处理方式
if (root.left == null && root.right == null) {
root.val = 1;
return;
}
// 处理非叶子节点
if (root.left != null) {
root.val = 0;
calculateNodeDeep(root.left);
}
if (root.right != null) {
root.val = 0;
calculateNodeDeep(root.right);
}
// 判断此时根节点的深度
if (root.right != null && root.left != null) {
if (root.right.val > root.left.val) {
root.val = root.right.val + 1;
} else {
root.val = root.left.val + 1;
}
} else if (root.right != null) {
root.val = root.right.val + 1;
} else {
root.val = root.left.val + 1;
}
}
// 先序遍历方式
public void preOder(TreeNode root) {
// 叶子节点处理方式
if (root.left == null && root.right == null) {
System.out.println(root.val);
return;
}
// 处理非叶子节点
if (root.left != null) {
System.out.println(root.val);
preOder(root.left);
}
if (root.right != null) {
System.out.println(root.val);
preOder(root.right);
}
}
// 判断是否为平衡二叉树
public void isBalanceBinaryTree(TreeNode root,int isTrue) {
if(isTrue == 0){
return;
}
// 叶子节点处理方式
if (root.left == null && root.right == null) {
System.out.println(root.val);
return;
}
// 处理非叶子节点
if (root.left != null) {
System.out.println(root.val);
isBalanceBinaryTree(root.left,isTrue);
}
if (root.right != null) {
System.out.println(root.val);
isBalanceBinaryTree(root.right,isTrue);
}
if (root.left != null && root.right != null) {
if (Math.abs(root.left.val - root.right.val) > 1) {
isTrue = 0;
return ;
}
}else if (root.right != null){
if(root.right.val >= 2){
}
}else {
if (root.left.val >= 2){
isTrue = 0;
return ;
}
}
}
}
leecode判断是否为平衡二叉树(demo待完善)
猜你喜欢
转载自blog.csdn.net/qq_42664961/article/details/109694421
今日推荐
周排行