您的位置:首页 > 其它

Search the Nth element of Level M in a binary tree

2013-06-26 21:24 387 查看
// binTreeMN.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <cstdio>
using namespace std;

struct Node{
int val;
Node *lChild;
Node *rChild;

Node(int v)
{
val = v;
lChild = NULL;
rChild = NULL;
}
};

void init_Tree(Node *&root, int *arr, int begin, int end)
{
if(begin > end)
return;
int mid = begin + (end-begin)/2;

if(root == NULL)
{
root = new Node(arr[mid]);
}

cout<<arr[mid]<<" ";
init_Tree(root->lChild, arr, begin, mid-1);
init_Tree(root->rChild, arr, mid+1, end);
}

void travel(Node *root)
{
if(root != NULL)
{
travel(root->lChild);
cout<<root->val<<" ";
travel(root->rChild);
}
}

bool print_MN(Node *root, int m, int n, int &count)
{
if(!root || m<0 || n<0)
return false;

if(m == 0)
{
if(count == n)
{
printf("val = %d", root->val);
return true;
}

count++;
return 0;
}

return print_MN(root->lChild, m-1, n, count) || print_MN(root->rChild, m-1, n, count);
}

/*
5
/ \
2   8
/ \ / \
1  3 6  9
\ \  \
4 6  0
*/
int main(int argc, char* argv[])
{
int test[] = {1,2,3,4,5,6,7,8,9,0};
int m = 2;
int n = 3;
int count = 0;
Node *root = NULL;
init_Tree(root, test, 0, 9);
cout<<endl<<"------In-Order travel------"<<endl;
travel(root);
cout<<endl<<"------("<<m<<","<<n<<")------"<<endl;
print_MN(root, m, n, count);

//printf("Hello World!\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: