在二叉树中找出和为某一值的所有路径

本文探讨了如何在二元树中寻找所有节点值之和等于特定整数的路径。通过递归算法实现路径的遍历与求和,最终打印出符合条件的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

程序员面试题精选(04)-在二元树中找出和为某一值的所有路径
题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。
例如输入整数22和如下二元树
                                            10
                                           /   /
                                          5     12
                                        /   /   
                                      4     7  
则打印出两条路径:10, 1210, 5, 7
二元树结点的数据结构定义为:
struct BinaryTreeNode // a node in the binary tree
{
      int              m_nValue; // value of node
      BinaryTreeNode  *m_pLeft;  // left child of node
      BinaryTreeNode  *m_pRight; // right child of node
};
分析:这是百度的一道笔试题,考查对树这种基本数据结构以及递归函数的理解。
当访问到某一结点时,把该结点添加到路径上,并累加当前结点的值。如果当前结点为叶结点并且当前路径的和刚好等于输入的整数,则当前的路径符合要求,我们把它打印出来。如果当前结点不是叶结点,则继续访问它的子结点。当前结点访问结束后,递归函数将自动回到父结点。因此我们在函数退出之前要在路径上删除当前结点并减去当前结点的值,以确保返回父结点时路径刚好是根结点到父结点的路径。我们不难看出保存路径的数据结构实际上是一个栈结构,因为路径要与递归调用状态一致,而递归调用本质就是一个压栈和出栈的过程。
参考代码:
///////////////////////////////////////////////////////////////////////
// Find paths whose sum equal to expected sum
///////////////////////////////////////////////////////////////////////
void FindPath
(
      BinaryTreeNode*   pTreeNode,    // a node of binary tree
      int               expectedSum,  // the expected sum
      std::vector<int>& path,         // a path from root to current node
      int&              currentSum    // the sum of path
)
{
      if(!pTreeNode)
            return;
      currentSum += pTreeNode->m_nValue;
      path.push_back(pTreeNode->m_nValue);
      // if the node is a leaf, and the sum is same as pre-defined,
      // the path is what we want. print the path
      bool isLeaf = (!pTreeNode->m_pLeft && !pTreeNode->m_pRight);
      if(currentSum == expectedSum && isLeaf)
      {   
           std::vector<int>::iterator iter = path.begin();
           for(; iter != path.end(); ++ iter)
                 std::cout << *iter << '/t';
           std::cout << std::endl;
      }

      // if the node is not a leaf, goto its children
      if(pTreeNode->m_pLeft)
            FindPath(pTreeNode->m_pLeft, expectedSum, path, currentSum);
      if(pTreeNode->m_pRight)
            FindPath(pTreeNode->m_pRight, expectedSum, path, currentSum);

      // when we finish visiting a node and return to its parent node,
      // we should delete this node from the path and
      // minus the node's value from the current sum
      currentSum -= pTreeNode->m_nValue;
      path.pop_back();
}
以下是使用C语言实现在二叉树找出为某的所有路径的示例代码: ```c #include <stdio.h> #include <stdlib.h> typedef struct TreeNode { int val; struct TreeNode* left; struct TreeNode* right; } TreeNode; void findPath(TreeNode* root, int sum, int* path, int depth) { if (root == NULL) { return; } path[depth] = root->val; int i, curSum = 0; for (i = depth; i >= 0; --i) { curSum += path[i]; if (curSum == sum) { int j; for (j = i; j < depth; ++j) { printf("%d->", path[j]); } printf("%d\n", path[depth]); } } findPath(root->left, sum, path, depth + 1); findPath(root->right, sum, path, depth + 1); } int main() { // 构造二叉树 TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode)); root->val = 10; root->left = (TreeNode*)malloc(sizeof(TreeNode)); root->left->val = 5; root->right = (TreeNode*)malloc(sizeof(TreeNode)); root->right->val = 12; root->left->left = (TreeNode*)malloc(sizeof(TreeNode)); root->left->left->val = 4; root->left->right = (TreeNode*)malloc(sizeof(TreeNode)); root->left->right->val = 7; // 在二叉树中查找为22的路径 int path[100]; findPath(root, 22, path, 0); // 释放二叉树空间 free(root->left->left); free(root->left->right); free(root->left); free(root->right); free(root); return 0; } ``` 该示例代码中,我们先构造了二叉树,并在其中查找为22的路径。在查找路径的过程中,我们使用了深度优先遍历的方法,通过个数组来保存当前已经走过的路径,每次遍历到个节点,则将该节点的加入路径中。在加入之后,我们检查路径中是否存在为目标的子路径,如果存在,则输出该路径。最后,我们递归遍历该节点的左子树右子树,以便查找所有可能的路径。 需要注意的是,该示例代码中并未考虑二叉树中存在负数的情况,如有需要,可以根据实际情况进行修改。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值