📜  在二叉树中以不降序的节点计数路径

📅  最后修改于: 2021-05-06 19:55:01             🧑  作者: Mango

给定一个由N个节点组成的二叉树,任务是查找从根到任意节点X的路径数,以使该路径中的所有节点值最多为X。

例子:

方法–使用DFS:想法是使用深度优先搜索遍历树,同时检查从根到任何节点X的最大值是否等于X。
请按照以下步骤解决问题:

  • 初始化一个变量,例如count0,以存储从根到任何节点X的路径计数,该路径中的所有节点值最多为X。
  • 使用深度优先搜索递归遍历树并执行以下步骤:
    • 除父节点外,对DFS遍历的每个递归调用都会传递该路径中到目前为止获得的节点的最大值。
    • 检查当前节点值是否大于或等于到目前为止获得的最大值,然后将count的值增加1并将最大值更新为当前节点值。
  • 完成上述步骤后,打印count的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
  
#include 
using namespace std;
  
// Node structure of the binary tree
struct Node {
    int val;
    Node *left, *right;
};
  
// Function for creating new node
struct Node* newNode(int data)
{
    // Allocate memory for new node
    struct Node* temp = new Node();
  
    // Assigning data value
    temp->val = data;
    temp->left = NULL;
    temp->right = NULL;
  
    // Return the Node
    return temp;
}
  
// Function to perform the DFS Traversal
// to find the number of paths having
// root to node X has value at most X
int countNodes(Node* root, int max)
{
    // If the root node is NULL
    if (!root)
        return 0;
  
    // Check if the current value is
    // greater than the maximum value
    // in path from root to current node
    if (root->val >= max)
        return 1 + countNodes(root->left,
                              root->val)
               + countNodes(root->right, root->val);
  
    // Otherwise
    return countNodes(root->left,
                      max)
           + countNodes(root->right,
                        max);
}
  
// Driver Code
int main()
{
    // Given Binary Tree
    Node* root = NULL;
    root = newNode(3);
    root->left = newNode(1);
    root->right = newNode(4);
    root->left->left = newNode(3);
    root->right->left = newNode(1);
    root->right->right = newNode(5);
  
    cout << countNodes(root, INT_MIN);
  
    return 0;
}


C++
// C++ program for the above approach
  
#include 
using namespace std;
  
// Node of the binary tree
struct Node {
    int val;
    Node *left, *right;
};
  
// Function for creating new node
struct Node* newNode(int data)
{
    // Allocate memory for new node
    struct Node* temp = new Node();
    temp->val = data;
    temp->left = NULL;
    temp->right = NULL;
  
    // Return the created node
    return temp;
}
  
// Function to perform the DFS Traversal
// to find the number of paths having
// root to node X has value at most X
int countNodes(Node* root)
{
    // Initialize queue
    queue > q;
    int m = INT_MIN;
  
    // Push root in queue with the
    // maximum value m
    q.push({ root, m });
  
    // Stores the count of good nodes
    int count = 0;
  
    // Traverse all nodes
    while (!q.empty()) {
  
        // Store the front node of
        // the queue
        auto temp = q.front();
        q.pop();
        Node* node = temp.first;
        int num = temp.second;
  
        // Check is current node is
        // greater than the maximum
        // value in path from root to
        // the current node
        if (node->val >= num)
            count++;
  
        // Update the maximum value m
        m = max(node->val, num);
  
        // If left child is not null,
        // push it to queue with the
        // maximum value m
        if (node->left)
            q.push({ node->left, m });
  
        // If right child is not null,
        // push it to queue with the
        // maximum value m
        if (node->right)
            q.push({ node->right, m });
    }
  
    // Returns the answer
    return count;
}
  
// Driver Code
int main()
{
    // Construct a Binary Tree
    Node* root = NULL;
    root = newNode(3);
    root->left = newNode(1);
    root->right = newNode(4);
    root->left->left = newNode(3);
    root->right->left = newNode(1);
    root->right->right = newNode(5);
  
    cout << countNodes(root);
  
    return 0;
}


输出:
4

时间复杂度: O(N)
辅助空间: O(N)

使用BFS的方法:想法是使用广度优先搜索遍历树,同时检查从根到X的最大值是否等于X。请按照以下步骤解决问题:

  • 初始化一个变量,例如说count0,以存储从根到具有该路径中所有节点值的任何节点X的路径计数,最多为X,并有成对的队列Q ,以执行BFS遍历。
  • 将以INT_MIN作为最大值的根节点推送到队列中。
  • 现在,直到Q为非空,执行以下操作:
    • 从队列中弹出前端节点。
    • 如果前端节点的值至少是到目前为止获得的当前最大值,则将count的值增加1
    • 用当前节点值更新到目前为止发生的最大值。
    • 如果当前弹出节点存在左右节点,则在上述步骤中将其以更新后的最大值推送到队列Q中。
  • 完成上述步骤后,打印count的值作为结果。

下面是上述方法的实现:

C++

// C++ program for the above approach
  
#include 
using namespace std;
  
// Node of the binary tree
struct Node {
    int val;
    Node *left, *right;
};
  
// Function for creating new node
struct Node* newNode(int data)
{
    // Allocate memory for new node
    struct Node* temp = new Node();
    temp->val = data;
    temp->left = NULL;
    temp->right = NULL;
  
    // Return the created node
    return temp;
}
  
// Function to perform the DFS Traversal
// to find the number of paths having
// root to node X has value at most X
int countNodes(Node* root)
{
    // Initialize queue
    queue > q;
    int m = INT_MIN;
  
    // Push root in queue with the
    // maximum value m
    q.push({ root, m });
  
    // Stores the count of good nodes
    int count = 0;
  
    // Traverse all nodes
    while (!q.empty()) {
  
        // Store the front node of
        // the queue
        auto temp = q.front();
        q.pop();
        Node* node = temp.first;
        int num = temp.second;
  
        // Check is current node is
        // greater than the maximum
        // value in path from root to
        // the current node
        if (node->val >= num)
            count++;
  
        // Update the maximum value m
        m = max(node->val, num);
  
        // If left child is not null,
        // push it to queue with the
        // maximum value m
        if (node->left)
            q.push({ node->left, m });
  
        // If right child is not null,
        // push it to queue with the
        // maximum value m
        if (node->right)
            q.push({ node->right, m });
    }
  
    // Returns the answer
    return count;
}
  
// Driver Code
int main()
{
    // Construct a Binary Tree
    Node* root = NULL;
    root = newNode(3);
    root->left = newNode(1);
    root->right = newNode(4);
    root->left->left = newNode(3);
    root->right->left = newNode(1);
    root->right->right = newNode(5);
  
    cout << countNodes(root);
  
    return 0;
}
输出:
4

时间复杂度: O(N)
辅助空间: O(N)