平衡二叉树的判断

来源:互联网 发布:算命最准的软件 编辑:程序博客网 时间:2024/06/04 18:15

判断二叉树是否为平衡二叉树

输入一颗二叉树,判断该二叉树是否是平衡二叉树

思路分析

  • 有了求二叉树的深度的经验,在遍历树的每一个节点的时候,调用函数TreeDepth得到它的左右子树的深度。如果每个节点的左右子树的深度相差都不超过1,则满足条件
  • 如果采用后序遍历的方式遍历二叉树的每一个节点,在遍历到一个节点之前就已经遍历了它的左右子树。只要在遍历每个节点时侯记录它的深度,即可判断每个节点是不是平衡

code

public class Solution{    public boolean IsBalanced_Solution(TreeNode root)    {        if(root==null)return true;//多次重复遍历节点        int left=TreeDepth(root.left);        int right=TreeDepth(root.right);        int diff=left-right;        if(diff<-1||diff>1)return  false;        return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);    }      public int TreeDepth(TreeNode root)    {        if(root==null)return 0;        else return Math.max(TreeDepth(root.left),TreeDepth(root.right))+1;    }}

每个节点只遍历一次的解法

public class Solution {    private boolean isBalanced=true;    public boolean IsBalanced_Solution(TreeNode root) {         getDepth(root);        return isBalanced;    }    public int getDepth(TreeNode root){        if(root==null)            return 0;        int left=getDepth(root.left);        int right=getDepth(root.right);        if(Math.abs(left-right)>1)            isBalanced=false;        return right>left?right+1:left+1;    }}
原创粉丝点击