题目描述:在二叉树中找到值最大的节点并输出
解题思路:将递归函数将二叉树遍历一遍,将节点与已知的值比较即可
实现代码:class Solution {
public:
/**
* @param root the root of binary tree
* @return the max node
*/
TreeNode* max=new TreeNode(-100000);
TreeNode* maxNode(TreeNode* root) {
// Write your code here
if(root==NULL) return NULL;
else {
if(root->val>max->val){max=root;}
maxNode(root->left);
maxNode(root->right);
}
return max;
}
};
感想:这题最重要的是这里 TreeNode* max=new TreeNode(-100000);将这个设置为全局变量,如果放在else后面 就是不过,因为每一次递归都会初始化max。设成全局的就好了。