1.題目
二叉樹根節點到葉子節點的節點序列稱爲路徑,如果路徑上所有節點和爲指定的某個數,就打印該路徑
10 / \ 5 12 /\ 4 7
有兩條路徑上的結點和爲22,分別是10+5+7和10+12
思路比較簡單:先序遍歷二叉樹,並同步更新直到當前節點爲止的sum和path,如果是葉子節點,與指定數比較,若相等,輸出序列
2.代碼
#include<stdio.h> #include<vector> struct BinaryTreeNode { int value; BinaryTreeNode* left; BinaryTreeNode* right; }; void doFindPath(BinaryTreeNode* root, int expect, std::vector& path, int& current) {//注意path和current是引用 current += root->value;//進入本節點,更新本節點對current和path的影響 path.push_back(root->value);//插入隊尾 bool isLeaf = root->left==NULL && root->right==NULL; if(isLeaf && current == expect)//打印結果 { std::vector::iterator iter = path.begin(); while(iter != path.end()) { printf("%d ", *iter); iter ++; } printf("\n"); } if(root->left) doFindPath(root->left, expect, path, current); if(root->right) doFindPath(root->right, expect, path, current); current -= root->value;//返回父節點時,刪除本節點造成的負面影響 path.pop_back(); } void findPath(BinaryTreeNode* root, int expect) { if(root == NULL) return; std::vector path; int current = 0; doFindPath(root, expect, path, current); }