📌  相关文章
📜  计算二叉树中最多相距K距离的叶节点对

📅  最后修改于: 2021-04-21 21:05:54             🧑  作者: Mango

给定一个二叉树和一个整数K ,任务是从给定的二叉树中计算可能的叶子节点对,以使它们之间的距离最大为K。

例子:

方法:想法是使用大小为K + 1的数组的后顺序遍历来跟踪具有特定距离的节点数。步骤如下:

  • 初始化大小为K + 1的数组arr [] ,其中arr [i]表示距离当前节点i的叶子节点的数量。
  • 然后,递归地更新上述数组,分别用于数组left []right []中每个节点的左子树和右子树。
  • 完成上述步骤后,对于每个节点,在对应索引处的left []和right []之间的距离将给出最左叶节点和最右叶节点之间的距离。将其在数组res []中更新为:
  • 现在,对于数组left []right []中所有可能的对(l,r) ,如果它们之间的距离之和最多为K ,则将对的计数增加为:

下面是上述方法的实现:

C++14
1
     / \
    2   3
   /
  4


Java
1
      / \
     2   3
    / \ / \
   4  5 6  7


Python3
// C++14 implementation of the
// above approach
#include 
using namespace std;
 
// Structure of a Node
struct Node
{
    int data;
    Node* left, *right;
 
    // Constructor of the class
    Node(int item)
    {
        data = item;
        left = right = NULL;
    }
};
 
// Stores the count of required pairs
int result = 0;
 
// Function to perform dfs to find pair of
// leaf nodes at most K distance apart
vector dfs(Node* root, int distance)
{
     
    // Return empty array if node is NULL
    if (root == NULL)
    {
        vector res(distance + 1, 0);
        return res;
    }
 
    // If node is a leaf node and return res
    if (root->left == NULL &&
       root->right == NULL)
    {
        vector res(distance + 1, 0);
        res[1]++;
        return res;
    }
 
    // Traverse to the left
    vector left = dfs(root->left,
                           distance);
 
    // Traverse to the right
    vector right = dfs(root->right,
                            distance);
 
    vector res(distance + 1, 0);
 
    // Update the distance between left
    // and right leaf node
    for(int i = res.size() - 2;
            i >= 1; i--)
        res[i + 1] = left[i]+ right[i];
 
    // Count all pair of leaf nodes
    // which are at most K distance apart
    for(int l = 1;l < left.size(); l++)
    {
        for(int r = 0;r < right.size(); r++)
        {
            if (l + r <= distance)
            {
                result += left[l] * right[r];
            }
        }
    }
 
    // Return res to parent node
    return res;
}
 
// Driver Code
int main()
{
     
    /*
         1
        / \
       2   3
      /
    4
    */
 
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
 
    // Given distance K
    int K = 3;
 
    // Function call
    dfs(root, K);
 
    cout << result;
}
 
// This code is contributed by mohit kumar 29


C#
// Java implementation of the
// above approach
 
// Structure of a Node
class Node {
    int data;
    Node left, right;
 
    // Constructor of the class
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
public class GFG {
    Node root;
 
    // Stores the count of required pairs
    static int result;
 
    // Function to perform dfs to find pair of
    // leaf nodes at most K distance apart
    static int[] dfs(Node root, int distance)
    {
        // Return empty array if node is null
        if (root == null)
            return new int[distance + 1];
 
        // If node is a leaf node and return res
        if (root.left == null
            && root.right == null) {
            int res[] = new int[distance + 1];
            res[1]++;
            return res;
        }
 
        // Traverse to the left
        int[] left = dfs(root.left,
                         distance);
 
        // Traverse to the right
        int[] right = dfs(root.right,
                          distance);
 
        int res[] = new int[distance + 1];
 
        // Update the distance between left
        // and right leaf node
        for (int i = res.length - 2;
             i >= 1; i--) {
            res[i + 1] = left[i]
                         + right[i];
        }
 
        // Count all pair of leaf nodes
        // which are at most K distance apart
        for (int l = 1;
             l < left.length; l++) {
 
            for (int r = 0;
                 r < right.length; r++) {
 
                if (l + r <= distance) {
                    result += left[l]
                              * right[r];
                }
            }
        }
 
        // Return res to parent node
        return res;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        GFG tree = new GFG();
 
        /*
                1
               /  \
             2     3
            / 
           4   
       */
 
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
 
        tree.root.left.left = new Node(4);
        result = 0;
 
        // Given distance K
        int K = 3;
 
        // Function Call
        dfs(tree.root, K);
 
        System.out.println(result);
    }
}


输出:
# Python3 implementation of the
# above approach
 
# Structure of a Node
class newNode:
     
    def __init__(self, item):
         
        self.data =  item
        self.left = None
        self.right = None
 
# Stores the count of required pairs
result = 0
 
# Function to perform dfs to find pair of
# leaf nodes at most K distance apart
def dfs(root, distance):
     
    global result
     
    # Return empty array if node is None
    if (root == None):
        res = [0 for i in range(distance + 1)]
        return res
 
    # If node is a leaf node and return res
    if (root.left == None and root.right == None):
        res = [0 for i in range(distance + 1)]
        res[1] += 1
        return res
 
    # Traverse to the left
    left = dfs(root.left, distance)
 
    # Traverse to the right
    right = dfs(root.right, distance)
 
    res = [0 for i in range(distance + 1)]
 
    # Update the distance between left
    # and right leaf node
    i = len(res) - 2
     
    while(i >= 1):
        res[i + 1] = left[i] + right[i]
        i -= 1
 
    # Count all pair of leaf nodes
    # which are at most K distance apart
    for l in range(1, len(left)):
        for r in range(len(right)):
            if (l + r <= distance):
                result += left[l] * right[r]
 
    # Return res to parent node
    return res
 
# Driver Code
if __name__ == '__main__':
     
    '''
         1
        / \
       2   3
      /
    4
    '''
    root = newNode(1)
    root.left = newNode(2)
    root.right = newNode(3)
    root.left.left = newNode(4)
 
    # Given distance K
    K = 3
 
    # Function call
    dfs(root, K)
 
    print(result)
 
# This code is contributed by ipg2016107

时间复杂度: O(N + E),其中N是二叉树中的节点数E是边数。辅助空间: O(H),其中H是二叉树的高度