用 C++ 找出二叉树中所有右节点的最大值


在这个教程中,我们得到一棵二叉树。我们的任务是找出二叉树中所有右节点的最大值。 

问题说明: 我们需要在这棵二叉树的右子节点中找出最大值。

举个例子来理解问题, 

输入: 


输出: 9

说明: 

所有右节点有:{2, 8, 9}。它们的最大值是 9。

解决方案

为了解决这个问题,我们需要遍历这棵树,并检查它是否有右子节点。如果有,就将它与 maxRight 元素进行比较,如果较大就进行替换。

演示我们解决方案的程序:

示例

在线演示

#include <iostream>
using namespace std;

struct Node {
   int data;
   struct Node *left, *right;
};

Node* newNode(int data) {
   
   Node* temp = new Node;
   temp->data = data;
   temp->left = temp->right = NULL;
   return temp;
}

int findMaxRightNode(Node* root) {
   
   int maxRight = -100;

   if (root == NULL)
      return -1;

   if (root->right != NULL)
      maxRight = root->right->data;

   return max( findMaxRightNode(root->right), max(maxRight, findMaxRightNode(root->left) ) );
}

int main() {

   Node* root = newNode(5);
   root->left = newNode(3);
   root->right = newNode(2);
   root->left->left = newNode(1);
   root->left->right = newNode(8);
   root->right->left = newNode(6);
   root->right->right = newNode(9);

   cout<<"The maximum among all right nodes in Binary Tree is "<< findMaxRightNode(root);

   return 0;
}

输出

The maximum among all right nodes in Binary Tree is 9

更新于:2021-01-25

55 次浏览

开启你的 职业生涯

完成课程以获得认证

立即开始
广告
© . All rights reserved.