二叉树的右视图
Posted HelloCoding08
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树的右视图相关的知识,希望对你有一定的参考价值。
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能 看到的节点值。
例如,给定如下二叉树: root = [ 3, 5 , 1, 6, 2, 9, 8, null, null,7 , 4 ]
返回: [3, 1, 8, 4]
int get_max(int left, int right) {
return left > right ? left : right;
}
typedef int ElemType;
typedef struct node Node;
typedef struct node* Tree;
struct node {
ElemType elem;
Node* lchild;
Node* rchild;
};
//创建树
Tree create_tree (FILE* fp) {
Tree tree;
ElemType elem;
fscanf(fp, "%d", &elem);
if (0 == elem) {
return NULL;
}
else {
tree = (Tree)malloc(sizeof(Node));
tree->elem = elem;
tree->lchild = create_tree(fp);
tree->rchild = create_tree(fp);
}
return tree;
}
//计算树的高度
int max_depth (Tree tree) {
if (tree == NULL) {
return 0;
}
//左孩子的高度与右孩子的高度的最大值加上根节点
int depth = get_max(max_depth(tree->lchild), max_depth(tree->rchild)) + 1;
return depth;
}
void dfs (Node* curr, int* result, int* index, int level) {
//递归的终止条件判断
if (curr == NULL) {
return;
}
//level表示的是第几层,因为是先遍历右子树,所以每一层最先遍历
if (*index == level) {
result[(*index)++] = curr->elem;
}
//先遍历右子树,在遍历左子树
dfs(curr->rchild, result, index, level + 1);
dfs(curr->lchild, result, index, level + 1);
}
int* right_side_view (Tree tree, int* size) {
int depth = max_depth(tree);
int* result = (int*)malloc(sizeof(int) * depth);
int index = 0;
int level = 0;
dfs(tree, result, &index, level);
*size = index;
return result;
}
int main () {
char path[] = "./demo.txt";
FILE* fp = fopen(path, "r");
if (fp == NULL) {
perror("fopen error");
exit(-1);
}
Tree tree = create_tree(fp);
fclose(fp);
int size = 0;
int* result = right_side_view(tree, &size);
for (int i = 0; i < size; i++) {
printf("%d\t", result[i]);
}
printf("\n");
return 0;
}
以上是关于二叉树的右视图的主要内容,如果未能解决你的问题,请参考以下文章