// ConsoleApplication11.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
typedef struct TreeNode
{
int data;
struct TreeNode * pLeft;
struct TreeNode * pRight;
}TreeNode;
typedef struct TreeNode* pTreeNode;
void InOrder(pTreeNode p); //中序遍历
int _tmain(int argc, _TCHAR* argv[])
{
TreeNode *pRoot = new TreeNode;
TreeNode *temp1 = new TreeNode;
TreeNode *temp2 = new TreeNode;
pRoot->data = 1;
pRoot->pLeft = NULL;
pRoot->pRight = NULL;
temp1->data = 2;
temp1->pLeft = NULL;
temp1->pRight = NULL;
temp2->data = 3;
temp2->pLeft = NULL;
temp2->pRight = NULL;
pRoot->pLeft = temp1;
pRoot->pRight = temp2;
InOrder(pRoot);
return 0;
}
void InOrder(pTreeNode p)
{
if (p == NULL)
return;
InOrder(p->pLeft);
cout << p->data;
InOrder(p->pRight);
}
计算二叉树的宽度
// 获取最大宽度 public static int getMaxWidth(TreeNode root) { if (root == null) return 0; Queue<TreeNode> queue = new ArrayDeque<TreeNode>(); int maxWitdth = 1; // 最大宽度 queue.add(root); // 入队 while (true) { int len = queue.size(); // 当前层的节点个数 if (len == 0) break; while (len > 0) {// 如果当前层,还有节点 TreeNode t = queue.poll(); len--; if (t.left != null) queue.add(t.left); // 下一层节点入队 if (t.right != null) queue.add(t.right);// 下一层节点入队 } maxWitdth = Math.max(maxWitdth, queue.size()); } return maxWitdth; }