How to determine if binary tree is balanced?

前端 未结 27 1488
萌比男神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 16:55

    class Node {
        int data;
        Node left;
        Node right;
    
        // assign variable with constructor
        public Node(int data) {
            this.data = data;
        }
    }
    
    public class BinaryTree {
    
        Node root;
    
        // get max depth
        public static int maxDepth(Node node) {
            if (node == null)
                return 0;
    
            return 1 + Math.max(maxDepth(node.left), maxDepth(node.right));
        }
    
        // get min depth
        public static int minDepth(Node node) {
            if (node == null)
                return 0;
    
            return 1 + Math.min(minDepth(node.left), minDepth(node.right));
        }
    
        // return max-min<=1 to check if tree balanced
        public boolean isBalanced(Node node) {
    
            if (Math.abs(maxDepth(node) - minDepth(node)) <= 1)
                return true;
    
            return false;
        }
    
        public static void main(String... strings) {
            BinaryTree tree = new BinaryTree();
            tree.root = new Node(1);
            tree.root.left = new Node(2);
            tree.root.right = new Node(3);
    
    
            if (tree.isBalanced(tree.root))
                System.out.println("Tree is balanced");
            else
                System.out.println("Tree is not balanced");
        }
    }
    

提交回复
热议问题