给定一个二叉树和一个整数K ,任务是检查树是否由一对总和正好为K的叶节点组成。如果有多对,打印其中任何一对。否则打印-1。
注意:假设给定的二叉树总是有 1 个以上的叶节点。
例子:
Input: X = 13
Output: [5, 8]
Explanation:
The given binary tree consists of 4 leaf nodes [4, 5, 6, 8].
The pair of nodes valued 5 and 8 have sum 13.
Input: X = 6
Output: [-1]
Explanation:
The given binary tree consists of 3 leaf nodes [4, 5, 3].
No valid pair of nodes exists whose sum of their values equal to 6.
Therefore, print -1.
朴素方法:解决问题的最简单方法是遍历树并将所有叶节点存储在一个数组中。然后对数组进行排序并使用两个指针技术来查找所需的对是否存在。
时间复杂度: O(NlogN)
辅助空间: O(N)
高效方法:上述方法可以使用HashSet进行优化。请按照以下步骤解决问题:
- 创建一个 Set 来存储叶节点的值。
- 遍历树,对于每个叶节点,检查无序集中是否存在(K – 叶节点的值) 。
- 如果发现为真,则打印节点值的 oair。
- 否则将当前节点的值存储到无序集合中。
下面是上述方法的实现:
C++
1
/ \
2 3
/ \ / \
4 5 6 7
\
8
Java
-1
/ \
2 3
/ \
4 5
Python3
// C++ Program to implement
// the above approach
#include
using namespace std;
// Stores if a pair exists or not
bool pairFound = false;
// Struct binary tree node
struct Node {
int data;
Node *left, *right;
};
// Creates a new node
Node* newNode(int data)
{
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Function to check if a pair of leaf
// nodes exists with sum K
void pairSum(Node* root, int target,
unordered_set& S)
{
// checks if root is NULL
if (!root)
return;
// Checks if the current node is a leaf node
if (!root->left and !root->right) {
// Checks for a valid pair of leaf nodes
if (S.count(target - root->data)) {
cout << target - root->data << " "
<< root->data;
pairFound = true;
return;
}
// Insert value of current node
// into the set
else
S.insert(root->data);
}
// Traverse left and right subtree
pairSum(root->left, target, S);
pairSum(root->right, target, S);
}
// Driver Code
int main()
{
// Construct binary tree
Node* root = newNode(1);
root->left = newNode(2);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right = newNode(3);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->right->right = newNode(8);
// Stores the leaf nodes
unordered_set S;
int K = 13;
pairSum(root, K, S);
if (pairFound == false)
cout << "-1";
return 0;
}
C#
// Java program to implement
// the above approach
import java.util.*;
class GFG{
// Stores if a pair exists or not
static boolean pairFound = false;
// Struct binary tree node
static class Node
{
int data;
Node left, right;
};
// Creates a new node
static Node newNode(int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
// Function to check if a pair of leaf
// nodes exists with sum K
static void pairSum(Node root, int target,
HashSet S)
{
// Checks if root is null
if (root == null)
return;
// Checks if the current node is a leaf node
if (root.left == null && root.right == null)
{
// Checks for a valid pair of leaf nodes
if (S.contains(target - root.data))
{
System.out.print(target - root.data +
" " + root.data);
pairFound = true;
return;
}
// Insert value of current node
// into the set
else
S.add(root.data);
}
// Traverse left and right subtree
pairSum(root.left, target, S);
pairSum(root.right, target, S);
}
// Driver Code
public static void main(String[] args)
{
// Construct binary tree
Node root = newNode(1);
root.left = newNode(2);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right = newNode(3);
root.right.left = newNode(6);
root.right.right = newNode(7);
root.right.right.right = newNode(8);
// Stores the leaf nodes
HashSet S = new HashSet();
int K = 13;
pairSum(root, K, S);
if (pairFound == false)
System.out.print("-1");
}
}
// This code is contributed by 29AjayKumar
输出:
# Python3 program to implement
# the above approach
# Stores if a pair exists or not
pairFound = False
S = set()
# Struct binary tree node
class newNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to check if a pair of
# leaf nodes exists with sum K
def pairSum(root, target):
global pairFound
global S
# Checks if root is NULL
if (root == None):
return
# Checks if the current node
# is a leaf node
if (root.left == None and
root.right == None):
temp = list(S)
# Checks for a valid pair of leaf nodes
if (temp.count(target - root.data)):
print(target - root.data, root.data)
pairFound = True
return
# Insert value of current node
# into the set
else:
S.add(root.data)
# Traverse left and right subtree
pairSum(root.left, target)
pairSum(root.right, target)
# Driver Code
if __name__ == '__main__':
# Construct binary tree
root = newNode(1)
root.left = newNode(2)
root.left.left = newNode(4)
root.left.right = newNode(5)
root.right = newNode(3)
root.right.left = newNode(6)
root.right.right = newNode(7)
root.right.right.right = newNode(8)
K = 13
pairSum(root, K)
if (pairFound == False):
print(-1)
# This code is contributed by bgangwar59
时间复杂度: O(N)
辅助空间: O(N)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live