本文主要是介绍【王道数据结构】【chapter5树与二叉树】【P159t13】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
假设二叉树采用二叉链表存储结构,设计一个算法,求非空二叉树b的宽度(即具有节点数最多的那一层的结点个数)
#include <iostream>
#include <stack>
#include <queue>
typedef struct treenode{char data;struct treenode *left;struct treenode *right;
}treenode,*ptreenode;ptreenode buytreenode(char x)
{ptreenode n=(ptreenode) malloc(sizeof (treenode));n->data=x;n->left= nullptr,n->right= nullptr;return n;
}
ptreenode build_tree()
{ptreenode root= buytreenode('A');root->left= buytreenode('B');root->right= buytreenode('C');root->left->left= buytreenode('D');root->left->right= buytreenode('E');root->right->left= buytreenode('F');root->right->right= buytreenode('G');root->left->left->left= buytreenode('H');root->left->left->right= buytreenode('I');return root;
}ptreenode build_tree2()
{ptreenode root= buytreenode('A');root->left= buytreenode('B');root->right= buytreenode('C');root->left->left= buytreenode('D');root->left->right= buytreenode('E');root->right->left= buytreenode('F');root->right->right= buytreenode('G');root->left->left->left= buytreenode('H');root->left->left->right= buytreenode('I');root->left->right->left= buytreenode('J');root->left->right->right= buytreenode('K');root->right->right->left= buytreenode('L');root->right->right->right= buytreenode('M');return root;
}void print_tree(ptreenode root) {std::queue<ptreenode> tmp;tmp.push(root);int s = tmp.size();while (!tmp.empty()) {ptreenode t = tmp.front();tmp.pop();s--;printf("%3c", t->data);if (t->left) tmp.push(t->left);if (t->right) tmp.push(t->right);if (s == 0) puts(""), s = tmp.size();}
}int widest(ptreenode root)
{if(root== nullptr) { return 0; }std::queue<ptreenode > record;record.push(root);int width=-1,size=record.size();while(!record.empty()){ptreenode head=record.front();record.pop();if(head->left) record.push(head->left);if(head->right) record.push(head->right);if(--size==0) size=record.size(),width=size>width?size:width;}return width;
}
int main() {ptreenode root=build_tree();print_tree(root);printf("%3d\n",widest(root));puts("");ptreenode root2=build_tree2();print_tree(root2);printf("%3d\n",widest(root2));return 0;
}
这篇关于【王道数据结构】【chapter5树与二叉树】【P159t13】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!