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; }
相关文章推荐
- Find the second largest element in a Binary Search Tree
- Find the nearest common ancestor of any two nodes in a binary search tree
- Find the common ancestor of two nodes in a binary tree
- Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never diffe
- [geeks]Two of the nodes of a Binary Search Tree (BST) are swapped. Fix (or correct) the BST
- Given preorder and inorder traversal of a tree, construct the binary tree.
- Simple implementation of the BinaryTree preorder traversal, inorder traversal, post traversal
- The implement of Binary Search Tree (JAVA)
- ch4.6: find the LCA of 2 nodes in a binary tree with 3 different methods
- [Google] print the outline of a complete binary tree in anti-clockwise direction
- Lowest Common Ancestor of The Two Nodes in a Binary Tree
- Compute the height of a binary search tree
- Get Level of a node in a Binary Tree
- Data Structure Binary Search Tree: Find k-th smallest element in BST (Order Statistics in BST)
- The Application of Two-level Attention Models in CNN for Fine-grained Image Classification
- eetcode_c++:树:Lowest Common Ancestor of a Binary Search Tree(235)
- 235. Lowest Common Ancestor of a Binary Search Tree
- Find the first repeating element in an array of integers
- 235. Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree