Sort by

recency

|

485 Discussions

|

  • + 0 comments

    Using Python 3’s pattern-matching:

    def getHeight(self, root):
        match root:
            case Node(left=None, right=None):
                return 0
            case Node(left=None):
                return 1 + self.getHeight(root.right)
            case Node(right=None):
                return 1 + self.getHeight(root.left)
            case _:
                return max(1 + self.getHeight(root.left), 1 + self.getHeight(root.right))
    
  • + 0 comments

    Python 3:

    def getHeight(self, root) -> int:
    		#Write your code here        
    		if root.left:
    				left = self.getHeight(root.left) + 1
    		else:
    				left = 0
    
    		if root.right:
    				right = self.getHeight(root.right) + 1
    		else:
    				right = 0
    
    		return max(left, right)
    
  • + 0 comments

    in TS

    class TreeNode {
        data: number
        left: TreeNode | null = null
        right: TreeNode | null = null
        
        constructor(n: number) {
            this.data = n
        }
    }
    
    class BinarySearchTree {
        root: TreeNode | null = null
    
        insert(root: TreeNode | null, data: number): void {
            if (root === null) {
                const newNode = new TreeNode(data);
                if (this.root === null) {
                    this.root = newNode;
                } else {
                    root = newNode;
                }
                return;
            }
    
            if (data <= root.data) {
                if (root.left) {
                    this.insert(root.left, data);
                } else {
                    root.left = new TreeNode(data);
                }
            } else {
                if (root.right) {
                    this.insert(root.right, data);
                } else {
                    root.right = new TreeNode(data);
                }
            }
        }
    
        getHeight(root: TreeNode | null): number {
            if (root === null) {
                return 0;
            }
    
            const leftHeight = this.getHeight(root.left);
            const rightHeight = this.getHeight(root.right);
            return Math.max(leftHeight, rightHeight) + 1;
        }      
    
    }
    
  • + 0 comments

    Python

    def getHeight(self, root):
            if not root.right and not root.left:
                return 0
            r_h = self.getHeight(root.right) if root.right else 0
            r_l = self.getHeight(root.left) if root.left else 0
            return max(r_h, r_l) + 1
    
  • + 0 comments

    Java solution

    public static int getHeight(Node root){
      //Write your code here
      int height = -1;
    
      if(root != null){
    
    
      int leftHeight = getHeight(root.left);
      int rightHeight = getHeight(root.right);
    
      height = Math.max(leftHeight, rightHeight) + 1;
      }
    
      return height;
    }