题目:输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
思路分析:
(1)首先该题是基于递归去遍历整棵树,遍历完每一条路径,遍历的顺序是先根节点,然后是左节点,接着是右节点;
(2)如果节点的左右子树都为空,且路径之和等于参数,就说明该路径是需要输出的
(3)如果不满足条件,在遍历完之后需要把最后一颗节点弹出来。
class Solution {
public:
void def(TreeNode* root,int expectNumber){
temp.push_back(root->val);
if(expectNumber - root->val ==0 &&
root->left == nullptr &&
root->right== nullptr)
{
ret.push_back(temp);
}
else{
if(root->left != nullptr){
def(root->left,expectNumber - root->val);
}
if(root->right != nullptr){
def(root->right,expectNumber - root->val);
}
}
temp.pop_back();
}
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if(root == nullptr){
return ret;
}
def(root,expectNumber);
return ret;
}
private:
vector<vector<int>>ret;
vector<int>temp;
};代码分析:
(1)25 行之所以要封装一个函数是因为,需要判断代码的鲁棒性(root是否等于nullptr),所以无法递归,必须要封装一层函数。
(2)28 行定义两个私有变量,ret 是最终返回的二级列表,而 temp是收集满足条件的路径,当路径满足条件时就赋值到ret 中,这一功能体现在第 9 行,而判断成立的条件就是左右节点为空,且路径之和等于参数 expectNumbe
(3)第19 行需要弹出最后的节点,是因为不满足条件,所以在每次返回上次层节点都需要弹出来。
用Python 实现
Python 思路和C++基本是一样的,代码整体也并不比C++简单
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# 判断鲁棒性
if not root:
return []
# 定义列表
result = []
def FindPathMain(root,path,currentNum):
# 每次的遍历都把节点加到path里面
currentNum += root.val
path.append(root)
# 左右两节点是否是空
isleaf = (root.left==None and root.right==None)
# 判断是否满足条件
if isleaf and currentNum == expectNumber:
onePath = []
for node in path:
onePath.append(node.val)
result.append(onePath)
if currentNum < expectNumber:
if root.left:
FindPathMain(root.left, path, currentNum)
if root.right:
FindPathMain(root.right, path, currentNum)
path.pop()
# 调用函数
FindPathMain(root, [], 0)
return result
京公网安备 11010502036488号