二叉树的深度和平衡二叉树

来源:互联网 发布:舞蹈扇子淘宝网 编辑:程序博客网 时间:2024/09/21 06:36

求平衡二叉树二叉树要用到二叉树的深度,所以将这两个算法放在一起。

首先来看球二叉树的深度。

题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

思路比较简单,就是递归比较左右子树的高度值,取较大的值。

//二叉数的数据结构public class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }}public int TreeDepth(TreeNode pRoot){    if(pRoot == null) return 0;    return Math.max(TreeDepth(pRoot.left)+1, TreeDepth(pRoot.right)+1);}

接下来看看判断一棵二叉树是不是平衡二叉树。

平衡二叉树具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

//二叉数的数据结构public class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }}public boolean IsBalanced_Solution(TreeNode root) {    if(root == null) return true;    if (Math.abs(getHeight(root.left) - getHeight(root.right)) > 1)        return false;    return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);}public int getHeight(TreeNode pRoot){    if(pRoot == null) return 0;    return Math.max(getHeight(pRoot.left)+1, getHeight(pRoot.right)+1);}
1 0
原创粉丝点击