Q 4.4 creates a linked list of all the nodes at each depth

Q: Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (i.e., if you have a tree with depth D, you’ll have D linked lists).

A:

思路1:逐層建立鏈表。

遍歷level層的節點,來建立level+1層的鏈表。即prev爲已level+1鏈表的尾節點,則level層的節點cur->left存在的話,將其插入到鏈表中,即prev->next = cur->left,同樣的道理查看cur->right,通過cur = cur->next,繼續建立鏈表。依此逐層進行。

思路2: BFS。同思路1,只是把用迭代實現。

#include <iostream>
#include <vector>
using namespace std;

struct TreeLinkNode {
	int val;
	TreeLinkNode *left, *right, *next;
	TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};

vector<TreeLinkNode*> res;

void insert(TreeLinkNode* root, int x){
    root = new TreeLinkNode(x);
    return ;
}

void connect1(TreeLinkNode *root) {
    if (!root) {
        return ;
    }
    TreeLinkNode dummy(-1);
    res.push_back(root);
    for (TreeLinkNode *cur = root, *prev = &dummy; cur; cur = cur->next) {
        if (cur->left) {
            prev->next = cur->left;
            prev = cur->left;
        }
        if (cur->right) {
            prev->next = cur->right;
            prev = cur->right;
        }
    }
    connect1(dummy.next);
}

void connect2(TreeLinkNode *root) {
    if (!root) {
        return ;
    }
    TreeLinkNode *cur = root;
    while (cur) {
        TreeLinkNode *next = NULL;
        TreeLinkNode *prev = NULL;
        while (cur) {
            if (!next) {
                if (cur->left) {
                    next = cur->left;
                } else if (cur->right) {
                    next = cur->right;
                }
            }
            if (cur->left) {
                if (!prev) {
                    prev = cur->left;
                }
                prev->next = cur->left;
                prev = prev->next;
            }
            if (cur->right) {
                if (!prev) {
                    prev = cur->right;
                }
                prev->next = cur->right;
                prev = prev->next;
            }
            cur = cur->next;
        }
        cur = next;
    }
}

int main() {
	int a[7] = {1,2,3,4,5,6,7};
	TreeLinkNode *root = new TreeLinkNode(a[0]);
//	cout<<root->val<<endl;
	int i = 1;
	root->left = new TreeLinkNode(a[i++]);
	root->right = new TreeLinkNode(a[i++]);
	root->left->left = new TreeLinkNode(a[i++]);
	root->left->right = new TreeLinkNode(a[i++]);
	root->right->left = new TreeLinkNode(a[i++]);
	root->right->right = new TreeLinkNode(a[i++]);
//	cout<<root->left->val<<endl;
	connect1(root);
	for (int i = 0; i < res.size(); i++) {
		TreeLinkNode *cur = res[i];
		while (cur) {
			cout<<cur->val<<" ";
			cur = cur->next;
		}
		cout<<endl;
	}
	return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章