Maximum binary tree node 632. (The change does not affect the value of the parameter argument)

Description
Find the maximum value of the node in the binary tree and returns.
Description
Chinese
English
to find the greatest value of the node in the binary tree and returns.

Sample
Sample 1:
Input:
1
/
-53
/ \ /
12-4-5
output: the value of node 3

Sample 2:
Input:
10
/
-52
/ \ /
03-4-5
output: the value of the node 10

public class Solution {
    /*
     * @param root: the root of tree
     * @return: the max node
     */
 
public TreeNode maxNode(TreeNode root) {
  
    TreeNode maxNode = root;
    if(root != null) {
        
        maxNode = getMaxNode(root,maxNode);
    }
    return maxNode;
}
public TreeNode getMaxNode(TreeNode root,TreeNode maxNode) {
    
    TreeNode leftNode = null;
    TreeNode rightNode = null;
    if(root.left != null) {
        leftNode = root.left;
        if(leftNode.val > maxNode.val) {
            maxNode = leftNode;
        }
       maxNode = getMaxNode(leftNode,maxNode);
    }
        
    if(root.right != null) {
        rightNode = root.right;
        if(rightNode.val > maxNode.val) {
            maxNode = rightNode;
        }
       maxNode = getMaxNode(rightNode,maxNode); // 形参的改变不影响实参的值!!所以要再赋值一遍
    }
    return maxNode;
}

}

Parameter change does not affect the value of the argument! ! ! !
Parameter change does not affect the value of the argument! ! ! !
Parameter change does not affect the value of the argument! ! ! !

Published 40 original articles · won praise 10 · views 30000 +

Guess you like

Origin blog.csdn.net/ai_pple/article/details/87189817