Recursively solve binary tree depth (height) (java)

Ideas

Recursively calculate the height of the left subtree and the right subtree, and then find the maximum of the heights of the two subtrees, add 1 to the height of the tree, similar to the preorder traversal

int heightOfBinaryTree(BinaryTreeNode root){
    
    
  int leftheight,rightheight;
  if(root == null)
    return 0;
  else{
    
    
    leftheight = heightOfBinaryTree(root.getLeft());
    rightheight = heightOfBinaryTree(root.getRight());
if(leftheight > rightheight){
    
    
    return leftheight+1;
  }
  return rightheight+1;
  }
}

Guess you like

Origin blog.csdn.net/weixin_37632716/article/details/110496753