二叉树的最大节点

来源:互联网 发布:linux查看文件前100行 编辑:程序博客网 时间:2024/06/09 23:21

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

分析:用递归遍历,整棵树,每一次递归的过程中逐次寻找较大的数并把此节点赋给临时指针,最后返回临时指针即为最大节点。

代码:

class Solution {public:    /**     * @param root the root of binary tree     * @return the max node     */     int max=-10000;     TreeNode* t;     TreeNode* maxNode(TreeNode* root) {        // Write your code here        if(root==NULL)            return NULL;        if(root->val>max)        {            max=root->val;            t=root;        }        maxNode(root->left);        maxNode(root->right);      return t;    }};


原创粉丝点击