-->
当前位置:首页 > 题库 > 正文内容

程序填空题:求二叉树值最大的结点

Luz4年前 (2021-05-10)题库1628
本题需要求出二叉树中值最大的结点并返回,请填空。例如,对于下面的二叉树,值最大的结点是3。
```c++
1
/ \
-5 2
/ \ / \
0 3 -4 -5
```

```c++
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 root;
TreeNode* max = root;
if (root->left) {
TreeNode* left = @@[maxNode(root->left)](3);
max = root->val > left->val ? root : left;
}
if (root->right) {
TreeNode* right = @@[maxNode(root->right)](3);
max = max->val > right->val ? max : right;
}
return max;
}
};
```






答案:
第1空:maxNode(root->left)

第2空:maxNode(root->right)

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。