打印带有指定和的从 C++ 中二叉树的根到任何路径
在这个问题中,我们得到一个二叉树和一个和 S。我们必须从根节点到该树的任何节点找到一条路径,该路径中所有节点的和等于给定的和。
输入
Sum = 14 Output : path : 4 10 4 3 7
要找到解决这个问题的方法,我们需要找到二叉树的前序遍历。然后找到等于给定和的路径。
例子
#include<bits/stdc++.h> using namespace std; struct Node{ int key; struct Node *left, *right; }; Node* insertNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp); } void printPathsUtilSum(Node* curr_node, int sum, int sum_so_far, vector<int> &path){ if (curr_node == NULL) return; sum_so_far += curr_node->key; path.push_back(curr_node->key); if (sum_so_far == sum ){ for (int i=0; i<path.size(); i++) cout<<path[i]<<"\t"; cout<<endl; } if (curr_node->left != NULL) printPathsUtilSum(curr_node->left, sum, sum_so_far, path); if (curr_node->right != NULL) printPathsUtilSum(curr_node->right, sum, sum_so_far, path); path.pop_back(); } void pathWithSum(Node *root, int sum){ vector<int> path; printPathsUtilSum(root, sum, 0, path); } int main (){ Node *root = insertNode(4); root->left = insertNode(10); root->right = insertNode(3); root->right->left = insertNode(7); root->right->right = insertNode(1); root->left->left = insertNode(8); root->left->right = insertNode(6); int sum = 14; cout<<"Paths with the given sum are : "<<endl; pathWithSum(root, sum); return 0; }
输出
和为给定和的路径有 −
4 10 4 3 7
广告