632.二叉树的最大节点

描述

在二叉树中寻找值最大的节点并返回。

您在真实的面试中是否遇到过这个题?  

样例

给出如下一棵二叉树:

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

返回值为 3 的节点。


入门难度:一个简单的遍历二叉树


/**
 * 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
        if(root==NULL) return NULL;
        TreeNode * maxVal=root;
        max(root,maxVal);
        return maxVal;
    }
    
    void max(TreeNode * root,TreeNode * &maxVal){
        if(root->val>maxVal->val) maxVal=root;
        if(root->left!=NULL) max(root->left,maxVal);
        if(root->right!=NULL) max(root->right,maxVal);
    }
};
本题算法虽然并没有难度,但是指针的运用却是关键。

猜你喜欢

转载自blog.csdn.net/vestlee/article/details/80322054