原文:

给定一棵二叉树和一个和 s ,打印所有路径,从根开始,求和到给定的和。 注意,这个问题与不同。这里的路径不需要在叶节点上结束。

示例:

input : 
input : sum = 8, 
        root of tree
         1
       /   \
     20      3
           /    \
         4       15    
        /  \     /  \
       6    7   8    9           
output :
path: 1 3 4
input : sum = 38,
        root of tree
          10
       /     \
     28       13
           /     \
         14       15
        /   \     /  \
       21   22   23   24
output : path found: 10 28 
        path found: 10 13 15

对于这个问题,前序遍历是最适合的,因为我们必须在到达那个节点时添加一个键值。 我们从根开始,通过前序遍历开始遍历,给 sum_so_far 加上键值,检查是否等于需要的和。 同样,由于树节点没有指向其父节点的指针,我们必须从我们移动的地方显式保存。我们使用向量路径来存储该路径。 该路径中的每个节点都有助于 sum_so_far。

c

// c   program to print all paths begiinning with
// root and sum as given sum
#include
using namespace std;
// a tree node
struct node
{
    int key;
    struct node *left, *right;
};
// utility function to create a new node
node* newnode(int key)
{
    node* temp = new node;
    temp->key = key;
    temp->left = temp->right = null;
    return (temp);
}
void printpathsutil(node* curr_node, int sum,
            int sum_so_far, vector &path)
{
    if (curr_node == null)
        return;
    // add the current node's value
    sum_so_far  = curr_node->key;
    // add the value to path
    path.push_back(curr_node->key);
    // print the required path
    if (sum_so_far == sum )
    {
        cout << "path found: ";
        for (int i=0; ileft != null)
        printpathsutil(curr_node->left, sum, sum_so_far, path);
    // if right child exists
    if (curr_node->right != null)
        printpathsutil(curr_node->right, sum, sum_so_far, path);
    // remove last element from path
    // and move back to parent
    path.pop_back();
}
// wrapper over printpathsutil
void printpaths(node *root, int sum)
{
    vector path;
    printpathsutil(root, sum, 0, path);
}
// driver program
int main ()
{
    /* 10
    /     \
    28     13
        /     \
        14     15
        / \     / \
    21 22 23 24*/
    node *root = newnode(10);
    root->left = newnode(28);
    root->right = newnode(13);
    root->right->left = newnode(14);
    root->right->right = newnode(15);
    root->right->left->left = newnode(21);
    root->right->left->right = newnode(22);
    root->right->right->left = newnode(23);
    root->right->right->right = newnode(24);
    int sum = 38;
    printpaths(root, sum);
    return 0;
}

java 语言(一种计算机语言,尤用于创建网站)

// java program to print all paths beginning
// with root and sum as given sum
import java.util.arraylist;
class graph{
// a tree node
static class node
{
    int key;
    node left, right;
};
// utility function to create a new node
static node newnode(int key)
{
    node temp = new node();
    temp.key = key;
    temp.left = temp.right = null;
    return (temp);
}
static void printpathsutil(node curr_node, int sum,
                           int sum_so_far,
                           arraylist path)
{
    if (curr_node == null)
        return;
    // add the current node's value
    sum_so_far  = curr_node.key;
    // add the value to path
    path.add(curr_node.key);
    // print the required path
    if (sum_so_far == sum)
    {
        system.out.print("path found: ");
        for(int i = 0; i < path.size(); i  )
            system.out.print(path.get(i)   " ");
        system.out.println();
    }
    // if left child exists
    if (curr_node.left != null)
        printpathsutil(curr_node.left, sum,
                       sum_so_far, path);
    // if right child exists
    if (curr_node.right != null)
        printpathsutil(curr_node.right, sum,
                       sum_so_far, path);
    // remove last element from path
    // and move back to parent
    path.remove(path.size() - 1);
}
// wrapper over printpathsutil
static void printpaths(node root, int sum)
{
    arraylist path = new arraylist<>();
    printpathsutil(root, sum, 0, path);
}
// driver code
public static void main(string[] args)
{
    /*    10
       /     \
     28       13
           /     \
         14       15
        /   \     /  \
       21   22   23   24*/
    node root = newnode(10);
    root.left = newnode(28);
    root.right = newnode(13);
    root.right.left = newnode(14);
    root.right.right = newnode(15);
    root.right.left.left = newnode(21);
    root.right.left.right = newnode(22);
    root.right.right.left = newnode(23);
    root.right.right.right = newnode(24);
    int sum = 38;
    printpaths(root, sum);
}
}
// this code is contributed by sanjeev2552

python 3

# python3 program to print all the
# paths from root, with a specified
# sum in binary tree
# binary tree node
""" utility that allocates a newnode
with the given key """
class newnode:
    # construct to create a newnode
    def __init__(self, key):
        self.key = key
        self.left = none
        self.right = none
# this function prints all paths
# that have sum k
def printpathsutil(curr_node, sum,
                sum_so_far, path):
    # empty node
    if (not curr_node) :
        return
    sum_so_far  = curr_node.key
    # add current node to the path
    path.append(curr_node.key)
    # print the required path
    if (sum_so_far == sum ) :
        print("path found:", end = " ")
        for i in range(len(path)):
            print(path[i], end = " ")
        print()
    # if left child exists
    if (curr_node.left != none) :
        printpathsutil(curr_node.left, sum,
                    sum_so_far, path)
    # if right child exists
    if (curr_node.right != none) :
        printpathsutil(curr_node.right, sum,
                    sum_so_far, path)
    # remove the current element
    # from the path
    path.pop(-1)
# a wrapper over printkpathutil()
def printpaths(root, sum):
    path = []
    printpathsutil(root, sum, 0, path)
# driver code
if __name__ == '__main__':
    """ 10
    /     \
    28     13
        /     \
        14     15
        / \     / \
    21 22 23 24"""
    root = newnode(10)
    root.left = newnode(28)
    root.right = newnode(13)
    root.right.left = newnode(14)
    root.right.right = newnode(15)
    root.right.left.left = newnode(21)
    root.right.left.right = newnode(22)
    root.right.right.left = newnode(23)
    root.right.right.right = newnode(24)
    sum = 38
    printpaths(root, sum)
# this code is contributed by
# shubham singh(shubhamsingh10)

java 描述语言


输出:

path found: 10 28 
path found: 10 13 15

本文由 供稿。如果你喜欢 geeksforgeeks 并想投稿,你也可以使用写一篇文章或者把你的文章邮寄到 review-team@geeksforgeeks.org。看到你的文章出现在极客博客pg电子试玩链接主页上,帮助其他极客。 如果发现有不正确的地方,或者想分享更多关于上述话题的信息,请写评论。