📌  相关文章
📜  计算二叉树中从根到自身的路径中具有最高值的节点

📅  最后修改于: 2021-09-06 06:27:03             🧑  作者: Mango

给定一棵二叉树,任务是计算二叉树中节点的数量,这些节点是从根到该节点的路径中价值最高的节点。

例子:

方法:思想是对给定的二叉树进行中序遍历,并在每次递归调用后更新路径中迄今为止获得的最大值节点。请按照以下步骤操作:

  • 对给定的二叉树执行中序遍历
  • 每次递归调用后,更新从根节点到当前节点的路径中迄今为止遇到的最大值节点。
  • 如果该节点的值超过目前路径中的最大值节点,则将计数增加1并更新到目前为止获得的最大值。
  • 继续到当前节点的子树。
  • 完全遍历二叉树后,打印得到的计数

下面是上述方法的实现:

C++14
// C++14 program for the above approach
#include 
using namespace std;
 
// Stores the ct of
// nodes which are maximum
// in the path from root
// to the current node
int ct = 0;
 
// Binary Tree Node
struct Node
{
    int val;
    Node *left, *right;
     
    Node(int x)
    {
        val = x;
        left = right = NULL;
    }
};
 
// Function that performs Inorder
// Traversal on the Binary Tree
void find(Node *root, int mx)
{
     
    // If root does not exist
    if (root == NULL)
      return;
     
    // Check if the node
    // satisfies the condition
    if (root->val >= mx)
        ct++;
     
    // Update the maximum value
    // and recursively traverse
    // left and right subtree
    find(root->left, max(mx, root->val));
     
    find(root->right, max(mx, root->val));
}
 
// Function that counts the good
// nodes in the given Binary Tree
int NodesMaxInPath(Node* root)
{
     
    // Perform inorder Traversal
    find(root, INT_MIN);
     
    // Return the final count
    return ct;
}
 
// Driver code
int main()
{
     
    /* A Binary Tree
              3
             / \
            2   5
           /     \
          4       6
        */
    Node* root = new Node(3);
    root->left = new Node(2);
    root->right = new Node(5);
    root->left->left = new Node(4);
    root->right->right = new Node(7);
     
    // Function call
    int answer = NodesMaxInPath(root);
     
    // Print the count of good nodes
    cout << (answer);
    return 0;
}
 
// This code is contributed by mohit kumar 29


Java
// Java program for the above approach
import java.util.*;
 
class GfG {
 
    // Stores the count of
    // nodes which are maximum
    // in the path from root
    // to the current node
    static int count = 0;
 
    // Binary Tree Node
    static class Node {
        int val;
        Node left, right;
    }
 
    // Function that performs Inorder
    // Traversal on the Binary Tree
    static void find(Node root, int max)
    {
        // If root does not exist
        if (root == null)
            return;
 
        // Check if the node
        // satisfies the condition
        if (root.val >= max)
            count++;
 
        // Update the maximum value
        // and recursively traverse
        // left and right subtree
        find(root.left,
             Math.max(max, root.val));
 
        find(root.right,
             Math.max(max, root.val));
    }
 
    // Function that counts the good
    // nodes in the given Binary Tree
    static int NodesMaxInPath(Node root)
    {
        // Perform inorder Traversal
        find(root, Integer.MIN_VALUE);
 
        // Return the final count
        return count;
    }
 
    // Function that add the new node
    // in the Binary Tree
    static Node newNode(int data)
    {
        Node temp = new Node();
        temp.val = data;
        temp.left = null;
        temp.right = null;
 
        // Return the node
        return temp;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        /* A Binary Tree
              3
             / \
            2   5
           /     \
          4       6
        */
 
        Node root = null;
        root = newNode(3);
        root.left = newNode(2);
        root.right = newNode(5);
        root.left.left = newNode(4);
        root.right.right = newNode(7);
 
        // Function Call
        int answer = NodesMaxInPath(root);
 
        // Print the count of good nodes
        System.out.println(answer);
    }
}


Python3
# Python 3 program for the
# above approach
import sys
 
# Stores the ct of
# nodes which are maximum
# in the path from root
# to the current node
ct = 0
 
# Binary Tree Node
class newNode:
   
    def __init__(self, x):
       
        self.val = x
        self.left = None
        self.right = None
 
# Function that performs Inorder
# Traversal on the Binary Tree
def find(root, mx):
   
    global ct
     
    # If root does not exist
    if (root == None):
        return
     
    # Check if the node
    # satisfies the condition
    if (root.val >= mx):
        ct += 1
     
    # Update the maximum value
    # and recursively traverse
    # left and right subtree
    find(root.left,
         max(mx, root.val))
     
    find(root.right,
         max(mx, root.val))
 
# Function that counts
# the good nodes in the
# given Binary Tree
def NodesMaxInPath(root):
   
    global ct
     
    # Perform inorder
    # Traversal
    find(root,
         -sys.maxsize-1)
     
    # Return the final count
    return ct
 
# Driver code
if __name__ == '__main__':
   
    '''
    /* A Binary Tree
              3
             / /
            2   5
           /     /
          4       6
        */
    '''
    root = newNode(3)
    root.left = newNode(2)
    root.right = newNode(5)
    root.left.left = newNode(4)
    root.right.right = newNode(7)
     
    # Function call
    answer = NodesMaxInPath(root)
     
    # Print the count of good nodes
    print(answer)
 
# This code is contributed by Surendra_Gangwar


C#
// C# program for
// the above approach
using System;
class GfG{
 
// Stores the count of
// nodes which are maximum
// in the path from root
// to the current node
static int count = 0;
 
// Binary Tree Node
public class Node
{
  public int val;
  public Node left,
              right;
}
 
// Function that performs
// Inorder Traversal on
// the Binary Tree
static void find(Node root,
                 int max)
{
  // If root does not exist
  if (root == null)
    return;
 
  // Check if the node
  // satisfies the condition
  if (root.val >= max)
    count++;
 
  // Update the maximum value
  // and recursively traverse
  // left and right subtree
  find(root.left,
  Math.Max(max, root.val));
 
  find(root.right,
  Math.Max(max, root.val));
}
 
    // Function that counts the good
    // nodes in the given Binary Tree
    static int NodesMaxInPath(Node root)
    {
        // Perform inorder Traversal
        find(root, int.MinValue);
 
        // Return the readonly count
        return count;
    }
 
// Function that add the new node
// in the Binary Tree
static Node newNode(int data)
{
  Node temp = new Node();
  temp.val = data;
  temp.left = null;
  temp.right = null;
 
  // Return the node
  return temp;
}
 
// Driver Code
public static void Main(String[] args)
{
  /* A Binary Tree
              3
             / \
            2   5
           /     \
          4       6
        */
 
  Node root = null;
  root = newNode(3);
  root.left = newNode(2);
  root.right = newNode(5);
  root.left.left = newNode(4);
  root.right.right = newNode(7);
 
  // Function Call
  int answer = NodesMaxInPath(root);
 
  // Print the count of good nodes
  Console.WriteLine(answer);
}
}
 
// This code is contributed by Princi Singh


输出:
4








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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live