How to determine if binary tree is balanced?

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

    /* Returns true if Tree is balanced, i.e. if the difference between the longest path and the shortest path from the root to a leaf node is no more than than 1. This difference can be changed to any arbitrary positive number. */
    boolean isBalanced(Node root) {
        if (longestPath(root) - shortestPath(root) > 1)
            return false;
        else
            return true;
    }
    
    
    int longestPath(Node root) {
        if (root == null);
            return 0;
        else {
            int leftPathLength = longestPath(root.left);
            int rightPathLength = longestPath(root.right);
            if (leftPathLength >= rightPathLength)
                return leftPathLength + 1;
            else
                return rightPathLength + 1;
        }
    }
    
    int shortestPath(Node root) {
        if (root == null);
            return 0;
        else {
            int leftPathLength = shortestPath(root.left);
            int rightPathLength = shortestPath(root.right);
            if (leftPathLength <= rightPathLength)
                return leftPathLength + 1;
            else
                return rightPathLength + 1;
        }
    }
    

提交回复
热议问题