Path Sum
来源:互联网 发布:适合程序员的机械键盘 编辑:程序博客网 时间:2024/06/08 06:49
1. 问题描述
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example:
Given the below binary tree and sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5]]
2. 思路
本质是二叉树的先序遍历! 先序遍历二叉树,将每次访问的节点值相加,直到叶子节点,然后判断这条到叶子节点的路径上所有节点的值的和是否和给定值相等,相等则将这条路径所有节点的值所组成的vector加入vecRet中。 存放路径显然是一个栈,题目中要求返回vector<vector<int>>,就将路径上的节点值放入vector<int>中,递归返回父节点的时候需要将节点从vector<int>中去掉。
3. 代码
vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int>> vecRet; if (root == NULL) return vecRet; int currentSum = 0; vector<int> path; pathSum (root , sum , currentSum , path , vecRet); return vecRet; } void pathSum (TreeNode* root , int sum , int currentSum , vector<int> &path , vector<vector<int>> &vecRet) { if (root == NULL) return ; TreeNode* pNode = root; path.push_back(pNode->val); currentSum += pNode->val; bool isLeaf = pNode->left == NULL && pNode->right == NULL; if (isLeaf && currentSum == sum) vecRet.push_back(path); if (pNode->left) pathSum (root->left , sum , currentSum , path , vecRet); if (pNode->right) pathSum (root->right ,sum , currentSum , path , vecRet); currentSum -= pNode->val; path.pop_back(); }
0 0
- Path Sum && Path Sum ||
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- Path Sum
- 笔记 MFC 打开或者保存路径浏览对话框(CFileDialog)
- JavaScript
- 五大内存分区
- Ubuntu 14.04 LTS 使用
- 做程序的第一年2014年总结
- Path Sum
- 解析Java中文乱码的处理方法
- Android Activity 生命周期
- 3-8 uva 202 Repeating Decimals
- uva10375(数论)
- 【安卓笔记】气泡式ListView
- 各个银行信用卡对比,办哪个银行的信用卡比较好?
- 深度学习基础(四)PCA和Whitening
- Linux下蓝牙耳机的配置与测试