How to determine if binary tree is balanced?

前端 未结 27 1526
萌比男神i
萌比男神i 2020-11-30 16:11

It\'s been a while from those school years. Got a job as IT specialist at a hospital. Trying to move to do some actual programming now. I\'m working on binary trees now, a

27条回答
  •  感动是毒
    2020-11-30 17:05

    public int height(Node node){
        if(node==null)return 0;
        else{
            int l=height(node.leftChild);
            int r=height(node.rightChild);
           return(l>r?l+1:r+1);
    
    }}
    public boolean balanced(Node n){
    
        int l= height(n.leftChild);
        int r= height(n.rightChild);
    
        System.out.println(l + " " +r);
        if(Math.abs(l-r)>1)
            return false;
        else 
            return true;
        }
    

提交回复
热议问题