Recursively find the largest element of a binary tree (java)

Ideas

A simple way to solve this problem is to use recursive thinking to find the largest element in the left subtree and the largest element in the right subtree respectively, and then compare it with the value of the node. The largest of these three values ​​is the problem. Solution, this method is easy to implement using recursion

int findMax(BinaryTreeNode root){
    
    
  int root_val,left,right,max=INT_MIN;
  if(root != null){
    
    
    root_val = root.getData();
    left = findMax(root.getLeft());
    right = findMax(root.getRight());
    //在三个值中找出最大值
    if(left > right){
    
    
      max = left;
    }else{
    
    
      max = right;
    }
    if(root_val > max){
    
    
      max = root_val;
    }
    return max;
  }


}

Guess you like

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