剑指offer:面试题34. 二叉树中和为某一值的路径
生活随笔
收集整理的這篇文章主要介紹了
剑指offer:面试题34. 二叉树中和为某一值的路径
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:二叉樹中和為某一值的路徑
輸入一棵二叉樹和一個整數,打印出二叉樹中節點值的和為輸入整數的所有路徑。從樹的根節點開始往下一直到葉節點所經過的節點形成一條路徑。
示例:
給定如下二叉樹,以及目標和?sum = 22,
? ? ? ? ? ? ? 5
? ? ? ? ? ? ?/ \
? ? ? ? ? ? 4 ? 8
? ? ? ? ? ?/ ? / \
? ? ? ? ? 11 ?13 ?4
? ? ? ? ?/ ?\ ? ?/ \
? ? ? ? 7 ? ?2 ?5 ? 1
返回:
[
? ?[5,4,11,2],
? ?[5,8,4,5]
]
解題:
二叉樹的先序遍歷的變形,也可以說是DFS
class Solution {
public:vector<vector<int>> pathSum(TreeNode* root, int sum) {vector<vector<int>> res;if(root==NULL) return res;vector<int> path;//使用vector作棧,使用它作棧來實現后進能夠先出FindPath(root, res, path, sum, 0);return res;}void FindPath(TreeNode* root, vector<vector<int>>& res,vector<int>& path,int expectedSum, int currentSum){currentSum += root->val;path.push_back(root->val);bool isLeaf=(root->left == NULL&&root->right==NULL);if (currentSum==expectedSum&&isLeaf)//如果當前值與給出的值相等,且該結點為葉子節點,則{res.push_back(path);//該路徑入棧}if (root->left != NULL) FindPath(root->left, res, path, expectedSum, currentSum);if (root->right != NULL) FindPath(root->right, res, path, expectedSum, currentSum);//返回父節點之前,在路徑上刪除當前結點path.pop_back();}
};
?
總結
以上是生活随笔為你收集整理的剑指offer:面试题34. 二叉树中和为某一值的路径的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剑指offer:面试题33. 二叉搜索树
- 下一篇: 剑指offer:面试题35. 复杂链表的