C++で相対位置があるすべてのルートからリーフへのパスを出力します
この問題では、二分木が与えられます。そして、ルートからツリーの葉までのすべてのパスを印刷する必要があります。 また、ノードの相対位置を示すためにアンダースコア「_」を追加します。
トピックをよりよく理解するために例を見てみましょう-
入力-
出力-
_ _ 3 _ 9 1 _3 9 _7 3 _ 4 _ _ 2 3 9 4 1 7 6 2 3 _ 4 6
この問題を解決するために、ツリーの要素の垂直方向の順序の概念を使用します。
これに基づいて、ルートからリーフへのパスを出力します。
アルゴリズム
Step 1: Traverse the binary tree using preorder traversal. And on traversal calculate the horizontal distance based on the order. The horizontal distance of root is 0 and processed as the above diagram. Step 2: And on traversing to the leaf node, print the path with an underscore “_” at the end.
例
#include<bits/stdc++.h>
using namespace std;
#define MAX_PATH_SIZE 1000
struct Node{
char data;
Node *left, *right;
};
Node * newNode(char data){
struct Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
struct PATH{
int horizontalDistance;
char key;
};
void printPath(vector < PATH > path, int size){
int minimumhorizontalDistance = INT_MAX;
PATH p;
for (int it=0; it<size; it++){
p = path[it];
minimumhorizontalDistance = min(minimumhorizontalDistance, p.horizontalDistance);
}
for (int it=0; it < size; it++){
p = path[it];
int noOfUnderScores = abs(p.horizontalDistance -minimumhorizontalDistance);
for (int i = 0; i < noOfUnderScores; i++) cout<<"_ ";
cout<<p.key<<endl;
}
cout<<"\nNext Path\n";
}
void printAllRtLPaths(Node *root, vector < PATH > &AllPath, int horizontalDistance, int order ){
if(root == NULL)
return;
if (root->left == NULL && root->right == NULL){
AllPath[order] = (PATH { horizontalDistance, root->data });
printPath(AllPath, order+1);
return;
}
AllPath[order] = (PATH { horizontalDistance, root->data });
printAllRtLPaths(root->left, AllPath, horizontalDistance-1, order+1);
printAllRtLPaths(root->right, AllPath, horizontalDistance+1, order+1);
}
void printRootToLeafPath(Node *root){
if (root == NULL)
return;
vector<PATH> Allpaths(MAX_PATH_SIZE);
printAllRtLPaths(root, Allpaths, 0, 0);
}
int main(){
Node *root = newNode('3');
root->left = newNode('9');
root->right = newNode('4');
root->left->left = newNode('1');
root->left->right = newNode('7');
root->right->left = newNode('6');
root->right->right = newNode('2');
printRootToLeafPath(root);
return 0;
} 出力
_ _ 3 _ 9 1 Next Path _ 3 9 _ 7 Next Path 3 _ 4 6 Next Path 3 _ 4 _ _ 2
-
C++を使用して再帰を使用せずにルートからリーフへのパスを出力するプログラム
このチュートリアルでは、ルートノードから特定のバイナリツリー内のすべてのリーフノードへのパスを出力するプログラムについて説明します。 たとえば、次の二分木があるとしましょう この二分木には、4つのリーフノードがあります。したがって、ルートノードからリーフノードへのパスは4つになります。 これを解決するために、反復アプローチを使用します。二分木のプレオーダートラバーサルを実行している間、マップに親ポインタを格納できます。トラバーサル中にリーフノードに遭遇したときはいつでも、親ポインタを使用してルートノードからそのパスを簡単に出力できます。 例 #include <bits/st
-
C ++プログラミングで再帰を使用せずに、ルートからリーフへのパスを出力します。
二分木を考えると、プログラムはルートからリーフまでの複数のパスを見つける必要があります。つまり、すべてのパスを出力する必要がありますが、再帰を使用しないことが課題です。 再帰なしで実行することが制約であるため、ツリーを繰り返しトラバースします。したがって、これを実現するために、ルート要素を格納するSTLマップを使用できます。リーフノードがレベル順トラバーサルによって識別されると、ルートノードを指すマップポインターがあるため、ルートからリーフへのパスが出力されます。 上記のツリーには、ルートからリーフに到達するために生成できる複数のパスがあります- 10 -> 3 ->