[面试备忘]求二叉树中节点最大距离 & 分层遍历二叉树

编程之美3.8-求二叉树中节点最大距离

编程之美3.10分层遍历二叉树

View Code
#include <iostream>
#include
<vector>
#include
<cstring>
#include
"general.h"


//编程之美3.8-求二叉树中节点最大距离-递归
int getMaxDepth(CPTNODE pNode) //求最大深度
{
if (pNode == NULL) {
return -1;
}
return 1 + MAX(getMaxDepth(pNode->left), getMaxDepth(pNode->right));
}

int getMaxDistance(CPTNODE pNode)//求最大点距离
{
if (pNode == NULL) {
return 0;
}
return MAX(MAX(getMaxDistance(pNode->left), getMaxDistance(pNode->right)),
2 + getMaxDepth(pNode->left) + getMaxDepth(pNode->right));
}

//分层遍历二叉树-普通方法
bool printNDepthNode(CPTNODE root, int length)
{
if (root == NULL) {
return false;
}
if (length == 0) {
std::cout
<< root->value << ' ';
return true;
}
return printNDepthNode(root->left, length - 1) + //not "||", shortcut!
printNDepthNode(root->right, length - 1);
}

void printNodeByDepth(CPTNODE root)
{
int depth = 0;
while(printNDepthNode(root, depth++)) {
std::cout
<< std::endl;
}
}

//分层遍历改进方法
void printNodeByDepthNew(CPTNODE root)
{
if (root == NULL) {
return;
}
std::vector
<CPTNODE> nodeVec;
nodeVec.push_back(root);
unsigned startFlag
= 0;
unsigned depthFlag
= nodeVec.size();
while (startFlag != nodeVec.size()) {
if (nodeVec[startFlag]->left != NULL) {
nodeVec.push_back(nodeVec[startFlag]
->left);
}
if (nodeVec[startFlag]->right != NULL) {
nodeVec.push_back(nodeVec[startFlag]
->right);
}
std::cout
<< nodeVec[startFlag]->value << ' ' << std::flush;
if (++startFlag == depthFlag) {
std::cout
<< std::endl;
depthFlag
= nodeVec.size();
}
}
}

int main()
{
char preOrder[] = "124853697";
char inOrder[] = "842516937";
PTNODE root
= NULL;
buildBinaryTree(preOrder, inOrder, strlen(preOrder), root);
std::cout
<< "Max Distance: " << getMaxDistance(root) << std::endl;
printNodeByDepth(root);
printNodeByDepthNew(root);
return 0;
}

分层遍历二叉树,如果想要从深层到浅层遍历,递归方法:先求二叉树深度,然后递减打印。

改进方法,先从浅到深分层将二叉树内数据压入数组,并记录每次分层边界下标,然后倒序打印。

如果即要从深到浅,而且从右到左,将数组倒序,然后正常打印。

posted @ 2011-09-06 10:28  lifengzhong  阅读(245)  评论(0编辑  收藏  举报