二叉树的最大节点-LintCode

来源:互联网 发布:c语言运算优先级 编辑:程序博客网 时间:2024/05/21 14:03

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

样例:
给出如下一棵二叉树:

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

返回值为 3 的节点。

#ifndef C632_H#define C632_H#include<iostream>using namespace std;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 *p = root;        if (root->left != NULL)            p = maxVal(p, maxNode(root->left));        if (root->right != NULL)            p = maxVal(p, maxNode(root->right));        return p;    }    TreeNode* maxVal(TreeNode *a, TreeNode  *b)    {        return a->val > b->val ? a : b;    }};#endif
原创粉丝点击