5.4.3—二叉树的递归—Path Sum

来源:互联网 发布:mmd双人动作数据 编辑:程序博客网 时间:2024/06/04 19:20
描述
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the
values along the path equals the given sum.
For example: Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

#include "BinaryTree.h"#include<algorithm>#include<vector>#include<stack>using namespace std;vector<int> path;//===判断一棵二叉树的路径和是否为给定的数--递归bool PathSum(BinaryTreeNode *proot, int k){if (!proot)return false;if (!proot->m_pLeft&&!proot->m_pRight&&proot->m_nValue == k)return true;if (PathSum(proot->m_pLeft, k - proot->m_nValue))return true;elsereturn PathSum(proot->m_pRight, k - proot->m_nValue);}// ====================测试代码====================//            8//        6      //      5   7  //   10  11//  9int main(){//===BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);BinaryTreeNode* pNode10 = CreateBinaryTreeNode(10);BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);BinaryTreeNode* pNode7 = CreateBinaryTreeNode(7);BinaryTreeNode* pNode9 = CreateBinaryTreeNode(9);BinaryTreeNode* pNode11 = CreateBinaryTreeNode(11);ConnectTreeNodes(pNode8, pNode6, NULL);ConnectTreeNodes(pNode6, pNode5, pNode7);ConnectTreeNodes(pNode5, pNode10, pNode11);ConnectTreeNodes(pNode10, pNode9, NULL);//===//PrintTree(pNode8);//===int k = 21;//===bool flag = PathSum(pNode8, k);cout << flag << endl;DestroyTree(pNode8);}