0
我正試圖通過一個「位串」來給出一個二叉樹的方向。我遇到的問題是,當它到達結尾時,從節點打印值(空),然後返回到頂部,直到「位串」中的特定字符在末尾被擊中。來自節點的打印值
因此字符串:
char * directions = "RRLRRLRLLRLRRS";
會從根開始,然後向右走>右>左>右(可以說是打一個假),那麼它就會回到根遍歷右>左> right> left> left(然後在每次發現葉子時切換回根目錄,然後一旦命中「S」就會停止遍歷)
我現在的代碼現在試圖從節點獲取值爲了調試的目的,最後命中並且它沒有打印任何東西。這怎麼能解決?
(訂單只是幫助確定在樹中它被定位)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
int order;
char value;
struct Node * left;
struct Node * right;
} Node;
Node * insert(Node * node, char value, int order){
if(node == NULL){
node = (Node *)malloc(sizeof(Node));
node->value = value;
node->order = order;
node->left = NULL;
node->right = NULL;
return node;
}
if(order > node->order){
node->right = insert(node->right, value, order);
}
else if(order < node->order){
node->left = insert(node->left, value, order);
}
else {
return;
}
return node;
}
int main(){
Node * root = NULL;
char * directions = "RRLRRLRLLRLRRS";
int length = (int)strlen(directions);
int i;
root = insert(root, -1, 6);
root = insert(root, -1, 4);
root = insert(root, -1, 2);
root = insert(root, 32, 1);
root = insert(root, 114, 3);
root = insert(root, 108, 5);
root = insert(root, -1, 12);
root = insert(root, -1, 8);
root = insert(root, 111, 7);
root = insert(root, -1, 10);
root = insert(root, 101, 9);
/* basics to see values at this point */
i = 0;
while(directions[i] != 'S'){
if(directions[i] == 'L'){
printf(root->value);
root = root->left;
}
else if(directions[i] == 'R'){
printf(root->value);
root = root->right;
}
i++;
}
return 0
}
這不會正確返回到原來的根,然後再次正確地遍歷。並應該是根 - >在最後的其他:) – user3362954
編輯我的答案,謝謝! –