Binary Tree Maximum Node(C++ Lincode)

解题思路:

(1)递归求解

/**
 * 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 root;
        auto *l=maxNode(root->left),*r=maxNode(root->right);
        return max_node(root,max_node(l,r));
    }
    
    TreeNode* max_node(TreeNode *a,TreeNode *b) {
        if (a==NULL) return b;
        if (b==NULL) return a;
        if (a->val>b->val) return a;
        else return b;
    }
};
发布了302 篇原创文章 · 获赞 277 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/105618810
今日推荐