判断二叉树是否为平衡二叉树,将java代码翻译为c++,c
public class IsBalancedTree {
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
public static class Info{
public boolean isBalanced;
public int height;
public Info(boolean isBalanced, int height) {
this.isBalanced = isBalanced;
this.height = height;
}
}
public static boolean isBalancedTree(Node head){
return process(head).isBalanced;
}
/*
* 平衡二叉树
* 向左树要信息,像右树要信息,当前节点解析处理返回
*/
private static Info process(Node head){
if (head == null) {
return new Info(true, 0);
}
Info leftInfo = process(head.left);
Info rightInfo = process(head.right);
int height = Math.max(leftInfo.height, rightInfo.height) + 1;
boolean isBalanced = leftInfo.isBalanced &&
rightInfo.isBalanced &&
Math.abs(leftInfo.height - rightInfo.height) < 2;
return new Info(isBalanced, height);
}
}