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.
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);}
阅读全文
0 0
- 5.4.3—二叉树的递归—Path Sum
- 5.4.4—二叉树的递归—Path Sum II
- 【LeetCode】Path Sum II 二叉树递归
- 【二叉树】437. Path Sum III(理解递归)
- 5.4.7—二叉树的递归—Sum Root to Leaf Numbers
- 二叉树 maximum path sum.
- 二叉树系列---path-sum
- 【二叉树】112. Path Sum
- leetcode 112. Path Sum(C语言,二叉树,递归思想)28
- Path Sum 判断二叉树的和 DFS处理
- [LintCode] 二叉树的路径之和 Binary Tree Path Sum
- Sum Root to Leaf Numbers 二叉树的path 和
- Path Sum 二叉树中和为某一值的路径
- LeetCode—***寻找二叉树中任意两个节点之间的最大值Binary Tree Maximum Path Sum
- leetcode_112. Path Sum 二叉树路径求和,判断是否存在路径和为某个值的路径,深度遍历,递归的return
- Path Sum 二叉树路径和 @LeetCode
- 二叉树-Binary tree maximum path sum
- Path Sum II 二叉树求和
- Oracle SQL语句优化
- docker学习笔记--重基础使用
- Wireshark图解教程(简介、抓包、过滤器)
- 5.4.2—二叉树的递归—Maximum Depth of Binary Tree
- 使用正则表达式控制input框输入类型
- 5.4.3—二叉树的递归—Path Sum
- 一流大学 VS. 工业部门
- ajax如何实现、readyState五中状态的含义
- 肝脏好
- textarea 操作
- 深入理解SpringMVC 参数映射
- 5.4.4—二叉树的递归—Path Sum II
- 虚拟机启动报内部错误解决
- 5.4.7—二叉树的递归—Sum Root to Leaf Numbers