【树】求全体二叉树结点最大值

思路:递归

  • 当前结点没有儿子结点时,最大值就是该结点的值
  • 如果有左右子树,将当前结点node和左右子树的最大值进行比较,选出较大的一个
  • 如果只有左(右)子树,则node的值与左(右)子树的最大值进行比较
 1 #include <iostream>
 2 #include <algorithm>
 3 using namespace std;
 4 
 5 struct TreeNode {
 6     int val;
 7     TreeNode *left;
 8     TreeNode *right;
 9     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
10 };
11 
12 int FindMaxNode(TreeNode* root) {
13     if (root == nullptr)
14         return NULL;
15     if (root->left == nullptr&&root->right == nullptr)
16         return root->val;
17     //左右子树不空
18     if (root->left != nullptr&&root->right != nullptr) {
19         int maxNode = max(root->val, FindMaxNode(root->left));
20         maxNode = max(maxNode, FindMaxNode(root->right));
21         return maxNode;
22     }
23     //只有一侧子树不空
24     if (root->left != nullptr&&root->right == nullptr)
25         return max(root->val, FindMaxNode(root->left));
26     if (root->left == nullptr&&root->right != nullptr)
27         return max(root->val, FindMaxNode(root->right));
28 }
29 /*
30       4
31     /   \
32    3     5
33   / \
34  1   2
35 */
36 
37 int main() {
38     //建树
39     TreeNode* T = new TreeNode(4);
40     T->left = new TreeNode(3);
41     T->right = new TreeNode(5);
42     T->left->left = new TreeNode(1);
43     T->left->right = new TreeNode(2);
44     cout << FindMaxNode(T)<<endl;
45     return 0;
46 }

 

posted @ 2020-04-25 21:37  PennyXia  阅读(1195)  评论(0编辑  收藏  举报