题目一:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,
- 最长路径的长度为树的深度。
- 输入:{1,2,3,4,5,#,6,#,#,7}
- 输出:4
//二叉树类
class BinaryTreeNode{
int value = 0;
BinaryTreeNode pLeft = null;
BinaryTreeNode pRight = null;
public BinaryTreeNode(int value){
this.value = value;
}
@Override
public String toString() {
return "BinaryTreeNode{" +
"value=" + value +
", pLeft=" + pLeft +
", pRight=" + pRight +
'}';
}
//计算深度
public static int treeDepth(BinaryTreeNode node){
if (node == null){
return 0;
}
int nLeft = treeDepth(node.pLeft);
int nRight = treeDepth(node.pRight);
return (nLeft>nRight)?(nLeft+1):(nRight+1);
}
//构建二叉树并计算深度
public static void main(String[] args) {
BinaryTreeNode pRoot = new BinaryTreeNode(1);
BinaryTreeNode p2 = new BinaryTreeNode(2);
BinaryTreeNode p3 = new BinaryTreeNode(3);
BinaryTreeNode p4 = new BinaryTreeNode(4);
BinaryTreeNode p5 = new BinaryTreeNode(5);
BinaryTreeNode p6 = new BinaryTreeNode(6);
BinaryTreeNode p7 = new BinaryTreeNode(7);
pRoot.pLeft = p2;
pRoot.pRight = p3;
p2.pLeft = p4;
p2.pRight = p5;
p5.pLeft = p7;
p3.pRight = p6;
int nDepth = treeDepth(pRoot);//计算深度
System.out.println(nDepth);
}
题目二:输入一棵二叉树,判断该二叉树是否是平衡二叉树。
- 在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
- 平衡二叉树(Balanced Binary Tree),具有以下性质:
- 它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
- 输入{1,2,3,4,5,6,7}
- 输出:true
/**
* 方法一:根据每个节点的左右子树的深度计算差值,若绝对值超过1则返回
* false.
* 相当于从上往下遍历,也就是从根节点开始判断每个节点的左右子树是否平
* 衡,节点会被重复遍历
* @param root
* @return
*/
public static boolean isBalanced(BinaryTreeNode root){
if (root == null){
return true;
}
int left = treeDepth(root.pLeft);//返回当前节点左子树的深度
int right = treeDepth(root.pRight);//返回当前节点右子树的深度
int diff = left - right;
if (diff > 1 || diff < -1){
return false;
}
return isBalanced(root.pLeft) && isBalanced(root.pRight);
}
/**
* 方法二:从下往上遍历,相当于是二叉树的后序遍历,即遍历到当前节点时
* 已经遍历完了它的左右子节点,并记录了当前深度,此时深度差大于1就返
* 回-1,一旦有节点左右不平衡返回-1就提前结束,不再遍历
* @param node
* @return
*/
public static int treeBlanced(BinaryTreeNode node){
if (node == null){
return 0;
}
int nLeft = treeBlanced(node.pLeft);
if (nLeft == -1){
return -1;
}
int nRight = treeBlanced(node.pRight);
if (nRight == -1){
return -1;
}
if ((nLeft - nRight) > 1 || (nLeft - nRight) < -1){
return -1;
}
return (nLeft>nRight)?(nLeft+1):(nRight+1);
}
//测试,返回值不为-1时即为平衡二叉树
public static void main(String[] args){
int depth = treeDepth(p1);
System.out.println(depth);
System.out.println(depth != -1);
}