Find the node with the largest value in the binary tree and return

Question: Find the node with the largest value in a binary tree and return it.

Sample

Given the following binary tree:

     1
   /   \
 -5     2
 / \   /  \
0   3 -4  -5 

Returns 3a .


Problem solving ideas:

1. Set the initial maximum value to root.

2. Use layer-order traversal. Accessing the binary tree is from top to bottom, and from left to right (FIFO).

3. Each time a node is visited, compare the current node with the original maximum node. If the value of the current node is greater than the value of the original maximum node, the original maximum node is replaced with the current node, otherwise it remains unchanged.

Code:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:

    /*
     * @param root: the root of tree
     * @return: the max node
     */
    TreeNode * maxNode(TreeNode * root) {
       
        // write your code here
        queue<TreeNode*> q;
        if(root != nullptr)
            q.push(root);
        TreeNode *pmaxNode = root;
        while(!q.empty()){
            TreeNode* front = q.front();
            if(pmaxNode->val < front->val){
                pmaxNode = front;
            }
            q.pop();
            if(front->left != nullptr)
                q.push(front->left);
            if(front->right != nullptr)
                q.push(front->right);
        }
        return pmaxNode;
       
       
       
    }
};




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324610997&siteId=291194637