Skip to content

2773. Height of Special Binary Tree 👎

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
 public:
  int heightOfTree(TreeNode* root) {
    if (root == nullptr)
      return 0;
    // a leaf node
    if (root->left != nullptr && root->left->right == root)
      return 0;
    return 1 + max(heightOfTree(root->left), heightOfTree(root->right));
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public int heightOfTree(TreeNode root) {
    if (root == null)
      return 0;
    // a leaf node
    if (root.left != null && root.left.right == root)
      return 0;
    return 1 + Math.max(heightOfTree(root.left), heightOfTree(root.right));
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def heightOfTree(self, root: TreeNode | None) -> int:
    if not root:
      return 0
    # a leaf node
    if root.left and root.left.right == root:
      return 0
    return 1 + max(self.heightOfTree(root.left), self.heightOfTree(root.right))