📌  相关文章
📜  与根和叶的距离为X的节点数

📅  最后修改于: 2021-05-04 15:11:35             🧑  作者: Mango

给定两个整数NX ,其中N是几乎完整的二叉树中的节点数。任务是找到:

  1. 距根X距离的节点数。
  2. 与其子树中的任何叶子X距离处的节点数。

注意: “完整二叉树”是一种二叉树,其中除最后一个级别外,每个级别都已完全填充,并且所有节点都尽可能地靠左。
例子:

Input: N = 6, X = 0
Output: 
1
3
Complete Binary Tree of 6 nodes is
         1
       /    \  
      2      3 
    /  \    / 
   4    5  6
Nodes that are at 0 distance from root = 1 (root itself).
Nodes that are at 0 distance from any of the leaf = 3 (all the leaves of the tree)

Input: N = 13, X = 1
Output:
2
4
Complete Binary Tree of 13 nodes.
                       1
                  /         \  
                2             3 
              /   \         /   \
            4      5       6     7
          /  \    /  \   /  \  
         8    9  10  11 12  13
Nodes that are at 0 distance from root = 2 (node no. 2 and 3)
Nodes that are at 0 distance from any of the leaf = 4 (node no. 4, 5, 6 and 3)

方法:

  1. 查找距根x距离的节点数很简单。我们只打印第x个高度的节点数。我们知道,在一棵完整的二叉树中,每个级别都是完整的,除了最后一个节点和所有节点都尽可能地靠左。因此,完整二叉树的高度h计算为floor(log2(n)) ,其中n是节点总数。同样,第i个高度的节点数为2 i ,而最后一级(即,高度h)的节点数= 2 h –(max_total_nodes – n) ,其中2 h是高度h的最大节点数。
  2. 查找与其子树中的任何叶子相距x距离的节点数有些棘手。关于观察到这样的事实:如果我们有l个叶节点,则ceil(l / 2)节点与叶的距离为1个单位距离, ceil(l / 4)节点与叶的距离为2个单位的距离……。直到ceil(l / 2 i )节点距叶子的i单位距离为止。我们将首先找到叶节点的数量,然后应用上述方法来查找距叶x距离的节点。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to find the count
// of the required nodes
void countNodes(int N, int X)
{
 
    // Height of the complete binary
    // tree with n nodes
    int height = floor(log2(N));
 
    // If X > height then no node
    // can be present at that level
    if (X > height) {
        cout << "0\n0";
        return;
    }
 
    // Corner case
    if (N == 1) {
        cout << "1\n1";
        return;
    }
 
    // Maximum total nodes that are possible
    // in complete binary tree with height h
    int max_total_nodes = (1 << (height + 1)) - 1;
 
    // Nodes at the last level
    int nodes_last_level
        = (1 << height) - (max_total_nodes - N);
 
    // To store the count of nodes
    // x dist away from root
    int from_root;
 
    // To store the count of nodes
    // x dist away from leaf
    int from_leaf;
 
    // If X = h then print nodes at last level
    // else nodes at Xth level
    if (X == height)
        from_root = nodes_last_level;
 
    // 2^X
    else
        from_root = 1 << X;
 
    // Number of left leaf nodes at (h-1)th level
    // observe that if nodes are not present at last level
    // then there are a/2 leaf nodes at (h-1)th level
    int left_leaf_nodes
        = ((1 << height) - nodes_last_level) / 2;
 
    // If X = h then print leaf nodes at the last h level
    // + leaf nodes at (h-1)th level
    if (X == 0) {
        from_leaf = nodes_last_level + left_leaf_nodes;
    }
    else {
 
        // First calculate nodes for leaves present at
        // height h
        int i = X;
 
        while (nodes_last_level > 1 && i > 0) {
            nodes_last_level
                = ceil((float)nodes_last_level / (float)2);
            i--;
        }
 
        from_leaf = nodes_last_level;
 
        // Then calculate nodes for leaves present at height
        // h-1
        i = X;
        while (left_leaf_nodes > 1 && i > 0) {
            left_leaf_nodes
                = ceil((float)left_leaf_nodes / (float)2);
            i--;
        }
 
        // Add both the resuls
        from_leaf += left_leaf_nodes;
    }
 
    cout << from_root << endl << from_leaf;
}
 
// Driver code
int main()
{
    int N = 38, X = 3;
 
    countNodes(N, X);
 
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
 
class GFG {
 
    // Function to find the count
    // of the required nodes
    static void countNodes(int N, int X)
    {
 
        // Height of the complete binary
        // tree with n nodes
        int height
            = (int)Math.floor(Math.log(N) / Math.log(2));
 
        // If X > height then no node
        // can be present at that level
        if (X > height) {
            System.out.println("0\n0");
            return;
        }
 
        // Corner case
        if (N == 1) {
            System.out.println("1\n1");
            return;
        }
 
        // Maximum total nodes that are possible
        // in complete binary tree with height h
        int max_total_nodes = (1 << (height + 1)) - 1;
 
        // Nodes at the last level
        int nodes_last_level
            = (1 << height) - (max_total_nodes - N);
 
        // To store the count of nodes
        // x dist away from root
        int from_root;
 
        // To store the count of nodes
        // x dist away from leaf
        int from_leaf;
 
        // If X = h then print nodes at last level
        // else nodes at Xth level
        if (X == height)
            from_root = nodes_last_level;
 
        // 2^X
        else
            from_root = 1 << X;
 
        // Number of left leaf nodes at (h-1)th level
        // observe that if nodes are not present at last
        // level then there are a/2 leaf nodes at (h-1)th
        // level
        int left_leaf_nodes
            = ((1 << height) - nodes_last_level) / 2;
 
        // If X = h then print leaf nodes at the last h
        // level
        // + leaf nodes at (h-1)th level
        if (X == 0) {
            from_leaf = nodes_last_level + left_leaf_nodes;
        }
        else {
 
            // First calculate nodes for leaves present at
            // height h
            int i = X;
 
            while (nodes_last_level > 1 && i > 0) {
                nodes_last_level = (int)Math.ceil(
                    (float)nodes_last_level / (float)2);
                i--;
            }
 
            from_leaf = nodes_last_level;
 
            // Then calculate nodes for leaves present at
            // height h-1
            i = X;
            while (left_leaf_nodes > 1 && i > 0) {
                left_leaf_nodes = (int)Math.ceil(
                    (float)left_leaf_nodes / (float)2);
                i--;
            }
 
            // Add both the resuls
            from_leaf += left_leaf_nodes;
        }
 
        System.out.println(from_root + "\n" + from_leaf);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 38, X = 3;
        countNodes(N, X);
    }
}
 
// This code is contributed by
// sanjeev2552


Python3
# Python3 implementation of the approach
from math import log2, ceil, floor
 
# Function to find the count
# of the required nodes
def countNodes(N, X):
 
    # Height of the complete binary
    # tree with n nodes
    height = floor(log2(N))
 
    # If X > height then no node
    # can be present at that level
    if (X > height):
        print("0\n0")
        return
 
    # Corner case
    if (N == 1):
        print("1\n1")
        return
 
    # Maximum total nodes that are possible
    # in complete binary tree with height h
    max_total_nodes = (1 << (height + 1)) - 1
 
    # Nodes at the last level
    nodes_last_level = (1 << height) - (max_total_nodes - N)
 
    # To store the count of nodes
    # x dist away from root
    from_root = 0
 
    # To store the count of nodes
    # x dist away from leaf
    from_leaf = 0
 
    # If X = h then prnodes at last level
    # else nodes at Xth level
    if (X == height):
        from_root = nodes_last_level
 
    # 2^X
    else:
        from_root = 1 << X
 
    # Number of left leaf nodes at (h-1)th level
    # observe that if nodes are not present at last level
    # then there are a/2 leaf nodes at (h-1)th level
    left_leaf_nodes = ((1 << height) - nodes_last_level) // 2
 
    # If X = h then prleaf nodes at the last h level
    # + leaf nodes at (h-1)th level
    if (X == 0):
        from_leaf = nodes_last_level + left_leaf_nodes
    else:
        # First calculate nodes for leaves present at
        # height h
        i = X
 
        while (nodes_last_level > 1 and i > 0):
            nodes_last_level = ceil(nodes_last_level / 2)
            i-=1
 
        from_leaf = nodes_last_level
 
        # Then calculate nodes for leaves present at height
        # h-1
        i = X
        while (left_leaf_nodes > 1 and i > 0):
            left_leaf_nodes = ceil(left_leaf_nodes / 2)
            i -= 1
 
        # Add both the resuls
        from_leaf += left_leaf_nodes
 
    print(from_root)
    print(from_leaf)
 
# Driver code
if __name__ == '__main__':
    N, X = 38, 3
 
    countNodes(N, X)
 
    # This code is contributed by mohit kumar 29.


输出:
8
3

时间复杂度: O(log(N))

辅助空间: O(1)