二叉樹中和為某一值的路徑 C

2021-10-04 06:04:39 字數 652 閱讀 2484

題目:

輸入一顆二叉樹的根節點和乙個整數,列印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。

思路:使用遞迴方法,從根節點出發,逐步向子節點遍歷,使用動態陣列儲存所經過的節點,並儲存每一步時當前的路徑節點之和,當到達葉節點時,該路徑上所有節點之和如果等於目標值,則儲存該路徑,並返回父節點,去判斷其他路徑

**如下:

/*

struct treenode

};*/

class solution

void findpath(treenode* root, int expectnumber, int cur_sum,

vector> &result, vector&path)

if(root->left != nullptr)

findpath(root->left, expectnumber, cur_sum, result, path);

if(root->right != nullptr)

findpath(root->right, expectnumber, cur_sum, result, path);

path.pop_back();

}};

二叉樹中和為某一值的路徑

include include using namespace std struct node void find path node r,int exceptedsum,vector path,int cursum node buildbtree int a,int i void preorder...

二叉樹中和為某一值的路徑

要輸出所有的路徑,必須額外用乙個棧來儲存當前路徑資訊。當訪問到節點a時,節點a的資訊要在訪問a的左右子樹時用到,因而,該資訊必須在遍歷a的左右子樹前加入到棧中,而在遍歷完a的左右子樹後從棧中移除。每訪問乙個節點,就計算當前路徑值 可直接利用父節點的路徑值 當其等於給定值且當前節點是葉子節點時,就列印...

二叉樹中和為某一值的路徑

面試題25 二叉樹中和為某一值的路徑 struct binarytreenode int value binarytreenode pleft binarytreenode pright 分析 用先序遍歷的方式遍歷二叉樹,初始時路徑為空。訪問乙個結點時若不到葉子結點且結點的和小於這個值那麼就把這個結...