How to determine if binary tree is balanced?

前端 未结 27 1485
萌比男神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:07

    To have a better performance specially on huge trees you can save the height in each node so it is a trade off space Vs performance:

    class Node {
        Node left;
        Node right;
        int value;
        int height;
    }
    

    Example of implementing the addition and same for deletion

    void addNode(Node root,int v)
    {    int height =0;
         while(root != null)
         {
             // Since we are adding new node so the height 
             // will increase by one in each node we will pass by
             root.height += 1;
             height++;
             else if(v > root.value){
                root = root.left();
                }
             else{
             root = root.right();
             }
    
         }
    
             height++;
             Node n = new Node(v , height);
             root = n;         
    }
    int treeMaxHeight(Node root)
    {
     return Math.Max(root.left.height,root.right.height);
    }
    
    int treeMinHeight(Node root)
    {
     return Math.Min(root.left.height,root.right.height);
    
    }
    
    Boolean isNodeBlanced(Node root)
    {
       if (treeMaxHeight(root) - treeMinHeight(root) > 2)
           return false;
    
      return true;
    }
    
    Boolean isTreeBlanced (Node root)
    {
        if(root == null || isTreeBalanced(root.left) && isTreeBalanced(root.right) && isNodeBlanced(root))
        return true;
    
      return false;
    
    }
    

提交回复
热议问题