問題描述:
在二叉樹中尋找值最大的節點並返回。
樣例
給出如下一棵二叉樹:
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
}
};
感想:
在定義新節點時寫在了函數內,造成每次遞歸調用時用一遍,使結果錯誤,且在初始化時要儘量小。