使用 C++ 列印完全二叉樹中從根節點到所有節點的路徑的程式
在本教程中,我們將討論一個程式,該程式用於列印從二叉樹的根節點到給定二叉樹中所有其他節點的路徑。
在這個程式中,我們將得到一個數字 N,表示二叉樹中存在的元素數量從 1 到 N;1 是二叉樹的根節點。因此,我們的任務是列印從根節點到二叉樹中存在的各種其他元素的所有可能路徑。
為了解決此程式,我們知道對於給定節點 I,其左子節點可以計算為 2*i,其右子節點可以計算為 2*i+1。然後,我們可以使用回溯法將該特定元素的路徑儲存在向量中,然後最終列印所有可能的路徑。
示例
#include <iostream> #include <vector> using namespace std; //calculating all the possible paths from the root node void calc_allpath(vector<int> paths, int nth_node, int kth_node){ if (kth_node > nth_node) return; paths.push_back(kth_node); for (int i = 0; i < paths.size(); i++) cout << paths[i] << " "; cout << endl; calc_allpath(paths, nth_node, kth_node * 2); calc_allpath(paths, nth_node, kth_node * 2 + 1); } //printing all the possible paths from the root node void print_allpath(int nth_node){ vector<int> paths; calc_allpath(paths, nth_node, 1); } int main(){ int nth_node = 9; print_allpath(nth_node); return 0; }
輸出
1 1 2 1 2 4 1 2 4 8 1 2 4 9 1 2 5 1 3 1 3 6 1 3 7
廣告