Lintcode 入门-632. 二叉树的最大节点

论坛 期权论坛 脚本     
已经匿名di用户   2022-5-29 18:54   2208   0
/**
 * 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) {
        if(root == NULL)
        {
            return NULL;
        }
        else
        {
            int p = root->val;
            getMax(root,&p);
            TreeNode* t = new TreeNode(p);
            return t;
        }
    }
    void getMax(TreeNode * root,int * p)
    {
        if(root != NULL)
        {
            if(root->val > *p)
            {
                *p = root->val;
            }
            getMax(root->left,p);
            getMax(root->right,p);
        }
        
    }
};

总结:①一种不同于由下至上最后比三定点,左最大,右最大的(三数比较)更高效的方法,将数中的每一个数沿着一种遍

历顺序与一个最大值进行比较,从而获得整个二叉树中的最大值。(实现上是用一个指针指向的int变量实现的,一开始想

用队列,栈那些,但觉得浪费,随后类比出一个整形变量而不需要更大的数据结构),②如果逻辑已经考虑到了所有情况,

但请确定你的代码和你的逻辑是吻合的,不然错误会出现的你毫无预料!








分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP