问题描述:
在二叉树中寻找值最大的节点并返回。
样例
给出如下一棵二叉树:
1
/ \
-5 2
/ \ / \
0 3 -4 -5
返回值为 3 的节点。
解决思路:
创建一个新的节点,将其与根节点比较,然后对左、右子树递归调用,得到结果。
代码:
class Solution { public: /** * @param root the root of binary tree * @return the max node */ TreeNode *max=new TreeNode(-100000); TreeNode *maxNode(TreeNode *root) { if(root==NULL) return NULL; else{ if(root->val>max->val) max=root; maxNode(root->left); maxNode(root->right); } return max; // Write your code here } };
感想:
在定义新节点时写在了函数内,造成每次递归调用时用一遍,使结果错误,且在初始化时要尽量小。
转载请注明原文地址: https://ju.6miu.com/read-600297.html