进阶之路

首页 新随笔 管理

19. 二叉树的镜像(递归)

 即:交换所有节点的左右子树。从下往上 或 从上往下 都可以。

#include <iostream>
#include <string>
using namespace std;
struct BTNode
{
	int v;  // default positive Integer.
	BTNode *pLeft;
	BTNode *pRight;
	BTNode(int x) : v(x), pLeft(NULL), pRight(NULL) {}
};
/********************************************************/
/*****        Basic functions          ***********/
BTNode* createBinaryTree(int r)
{
	BTNode *pRoot = new BTNode(r);
	int u, v;
	cin >> u >> v;
	if(u != 0)
		pRoot->pLeft = createBinaryTree(u);
	if(v != 0)
		pRoot->pRight = createBinaryTree(v);
	return pRoot;
}
void release(BTNode *root){
	if(root == NULL) return;
	release(root->pLeft);
	release(root->pRight);
	delete[] root;
	root = NULL;
}
void print(BTNode *root, int level = 1){
	if(root == NULL) { cout << "NULL"; return; };
	string s;
	for(int i = 0; i < level; ++i) s += "   ";
	cout << root->v << endl << s;
	print(root->pLeft, level+1);
	cout << endl << s;
	print(root->pRight, level+1);
}
/******************************************************************/
void mirrorTree(BTNode *root)
{
	if(!root || (!root->pLeft && !root->pRight)) return;
	/*    交换左右子树           */
	BTNode *pTem = root->pLeft; 
	root->pLeft = root->pRight;
	root->pRight = pTem;

	mirrorTree(root->pLeft);
	mirrorTree(root->pRight);
}


int main(){
	int TestTime = 3, k = 1;
	while(k <= TestTime)
	{
		cout << "Test " << k++ << ":" << endl;
		
		cout << "Create a tree: " << endl;
		BTNode *pRoot = createBinaryTree(8);
		print(pRoot);
		cout << endl;

		cout << "The mirror tree: " << endl;
		mirrorTree(pRoot);
		print(pRoot);
		cout << endl;

		release(pRoot);
	}
	return 0;
}

 

 20. 顺时针打印矩阵

 1 #include <stdio.h>
 2 
 3 void printMatrix(int (*A)[1], int rows, int columns)
 4 {
 5     if(rows < 1 || columns < 1) return;
 6     int r1, r2, c1, c2;
 7     r1 = c1 = 0, r2 = rows-1, c2 = columns-1;
 8     while(r1 <= r2 && c1 <= c2) /* 打印结束时, r1 = r2+1, c1 = c2+1; */
 9     {
10         for(int i = c1; i <= c2 && r1 <= r2; ++i)
11             printf("%d ", A[r1][i]);
12         ++r1;
13         for(int i = r1; c1 <= c2 && i <= r2; ++i)
14             printf("%d ", A[i][c2]);      /*   要保证 c1 <= c2  */      
15         --c2;
16         for(int i = c2; i >= c1 && r1 <= r2; --i)
17             printf("%d ", A[r2][i]);
18         --r2;
19         for(int i = r2; i >= r1 && c1 <= c2; --i)
20             printf("%d ", A[i][c1]);
21         ++c1;
22     }
23     printf("\n");
24 }
25 int main()
26 {
27     int test1[3][3] = {{1, 2, 3},
28                        {4, 5, 6}, 
29                         {7, 8, 9}};
30     printMatrix(test1, 3, 3);
31 
32     int test2[1][3] = {1, 2, 3};
33     printMatrix(test2, 1, 3);
34 
35 /*  // first set int (*A)[1], then began called below. 
36     int test3[3][1] = {{1}, {2}, {3}};
37     printMatrix(test3, 3, 1);
38 
39     int test4[1][1] = {1};
40     printMatrix(test4, 1, 1);
41 */
42     return 0;
43 }
View Code

      (

 21. 包含 min  函数的栈

 要求调用 min,pop,push,时间复杂度都是 O(1)。

 1 #include <iostream>
 2 #include <stack>
 3 #include <cassert>
 4 #include <string>
 5 template<typename T> class Stack
 6 {
 7 public:
 8     void push(T value);
 9     void pop();
10     T min();
11 private:
12     std::stack<T> data;
13     std::stack<T> minData;
14 };
15 template<typename T> void Stack<T>::push(T value)
16 {
17     data.push(value);
18     if(minData.empty() || minData.top() >= value)
19         minData.push(value);
20     else
21         minData.push(minData.top());
22 }
23 template<typename T> void Stack<T>::pop()
24 {
25     assert(data.size() > 0 && minData.size() > 0);
26     data.pop();
27     minData.pop();
28 }
29 template<typename T> T Stack<T>::min()
30 {
31     return minData.top();
32 }
33 
34 int main()
35 {
36     Stack<char> st;
37     std::string numbers;
38     while(std::cin >> numbers)
39     {
40         for(size_t i = 0; i < numbers.length(); ++i) st.push(numbers[i]);
41         for(size_t i = 0; i < numbers.length(); ++i)
42         {
43             std::cout << "st.min(): " << st.min() << std::endl;
44             st.pop();
45         }
46     }
47     return 0;
48 }
View Code

22. 根据栈的压入序列,判断一个序列是否是弹出序列。 

#include <iostream>
#include <string>

bool isPopOrder(const std::string pushS, const std::string popS)
{
	size_t outId1 = 0, outId2 = 0, len1 = pushS.length(), len2 = popS.length();
	if(len1 != len2) return false;
	int *stack = new int[len1];
	int tail = 0; // 栈尾 
	while(outId1 < len1 && outId2 < len2)
	{
		while(pushS[outId1] != popS[outId2])
		{
			stack[tail++] = pushS[outId1++]; // 入栈
		}
		outId1++, outId2++;
		while(tail != 0 && popS[outId2] == stack[tail-1])
		{
			++outId2;
			tail--;     // 出栈
		}
	}
	delete[] stack;
	if(tail == 0) return true; // 栈空
	else return false;
}

int main()
{
	std::string numbers;
	std::string popNumbers;
	while(std::cin >> numbers >> popNumbers)
	{
		std::cout << "一个弹出序列?   " ;

		if(isPopOrder(numbers, popNumbers))
			std::cout << "true" << std::endl;
		else std::cout << "false" << std::endl;
	}
	return 0;
}

 

23. 从上往下打印二叉树

 Go:(Chap2: question: 1 - 10—>6. 重建二叉树—>二叉树的各种遍历)Link: http://www.cnblogs.com/liyangguang1988/p/3667443.html

24. 判断序列是否为二叉搜索树的后序遍历(递归)

note: 二叉搜索树和遍历序列一一对应。

例:后序序列 {3,5,4,6,11,13,12, 10, 8} ,可画出一颗二叉搜索树。

 1 #include <iostream> 
 2 /* verify the seq which should be the postOrder of a Binary Search Tree  */
 3 bool postOrderOfBST(int sequence[], int len)
 4 {
 5     if(sequence == NULL || len == 0) return false;
 6     bool answer = false;
 7     int root = sequence[len-1];    /* value of root node */
 8 
 9     int leftLength = 0;
10     for(; leftLength < len-1; ++leftLength)
11     {
12         if(sequence[leftLength] > root) break;
13     }
14     /*  verify right-subtree, should big than root  */
15     for(int i = leftLength + 1; i < len -1; ++i)
16     {
17         if(sequence[i] < root) return false;
18     }
19 
20     int rightLength = len - 1 - leftLength;
21     bool left = true, right = true;
22     if(leftLength > 0)
23         bool left = postOrderOfBST(sequence, leftLength);
24     if(rightLength)
25         bool right = postOrderOfBST(sequence+leftLength, rightLength);
26     return (left && right);
27 }
28 
29 void printResult(bool v)
30 {
31     std::cout << "Is LRD of a BFS?  " ; 
32     if(v)  std::cout << "true" << std::endl;
33     else  std::cout << "false" << std::endl; 
34 }
35 int main() 
36 {
37     std::cout << "Test 1: ";
38     int test1[] = {3, 5, 4, 6, 11, 13, 12, 10, 8};
39     printResult(postOrderOfBST(test1, sizeof(test1) / 4)) ;
40 
41     std::cout << "Test 2: ";
42     int test2[] = {4, 2, 3}; 
43     printResult(postOrderOfBST(test2, sizeof(test2) / 4)); 
44         
45     std::cout << "Test 3: ";
46     int test3[] = {1};
47     printResult(postOrderOfBST(test3, sizeof(test3) / 4));
48 
49     return 0; 
50 } 
View Code

  

 25. 二叉树中和为某一值的路径(递归)

 1 #include <iostream> 
 2 #include <string>
 3 #include <vector>
 4 using namespace std; 
 5 struct BTNode 
 6 { 
 7     int v;  // default positive Integer. 
 8     BTNode *pLeft; 
 9     BTNode *pRight; 
10     BTNode(int x) : v(x), pLeft(NULL), pRight(NULL) {} 
11 }; 
12 /********************************************************/
13 /*****        Basic functions          ***********/
14 BTNode* createBinaryTree(int r) 
15 { 
16     BTNode *pRoot = new BTNode(r); 
17     int u, v; 
18     cin >> u >> v; 
19     if(u != 0) 
20         pRoot->pLeft = createBinaryTree(u); 
21     if(v != 0) 
22         pRoot->pRight = createBinaryTree(v); 
23     return pRoot; 
24 } 
25 void release(BTNode *root){ 
26     if(root == NULL) return; 
27     release(root->pLeft); 
28     release(root->pRight); 
29     delete[] root; 
30     root = NULL; 
31 } 
32 void print(BTNode *root, int level = 1){ 
33     if(root == NULL) { cout << "NULL"; return; }; 
34     string s; 
35     for(int i = 0; i < level; ++i) s += "\t"; 
36     cout << root->v << endl << s; 
37     print(root->pLeft, level+1); 
38     cout << endl << s; 
39     print(root->pRight, level+1); 
40 } 
41 /******************************************************************/
42 void findPath(BTNode *root, int target, vector<int>& path, int curSum)
43 {
44     if(root == NULL) return;
45     curSum += root->v;
46     path.push_back(root->v);
47     if(!root->pLeft && !root->pRight && (curSum == target))  // root node is a leaf, get a path.
48     {
49         for(auto it = path.begin(); it != path.end(); ++it)
50             cout << *it << " ";
51         cout << endl;
52     }
53     findPath(root->pLeft, target, path, curSum);
54     findPath(root->pRight, target, path, curSum);
55     path.pop_back();
56 }
57 
58 void findPath(BTNode *root, int target)
59 {
60     if(root == NULL) return;
61     vector<int> path;
62     findPath(root, target, path, 0);
63 }
64 
65 int main(){ 
66     int TestTime = 3, k = 1; 
67     while(k <= TestTime) 
68     { 
69         int root;
70         cout << "Test " << k++ << ":" << endl; 
71 
72         cout << "Create a tree: " << endl; 
73         cin >> root;
74         BTNode *pRoot = createBinaryTree(root); 
75         print(pRoot); 
76         cout << endl; 
77 
78         cout << "target :  22" << endl << "findPath :" << endl; 
79         findPath(pRoot, 22);
80 
81         release(pRoot); 
82     } 
83     return 0; 
84 } 
Code

 26. 复杂链表的复制

  1 #include <stdio.h>
  2 typedef char Elem; 
  3 typedef struct ComplexListNode
  4 {
  5     Elem e;
  6     ComplexListNode *next;
  7     ComplexListNode *sibling;
  8 } ComplexList;
  9 ComplexListNode Node[26] = {0};
 10 /***************************************************************/
 11 ComplexList* creatComplexList()
 12 {
 13     for(int i = 0; i < 26; ++i)
 14         Node[i].e = i + 'A';
 15     char u, v;
 16     while((scanf("%c%c", &u, &v) == 2) )
 17     {
 18         if(u >= 'A' && u <= 'Z' && v >= 'A' && v <= 'Z')
 19         {
 20             if(Node[u-'A'].next == NULL)
 21                 Node[u-'A'].next = &Node[v-'A'];
 22             else if(Node[u-'A'].sibling == NULL)
 23                 Node[u-'A'].sibling = &Node[v-'A'];
 24         }
 25         if(getchar() == '\n') break;
 26     }
 27     return &Node[0];
 28 }
 29 
 30 void printComplexList(ComplexList *pHead)
 31 {
 32     ComplexListNode *p = pHead;
 33     while(p != NULL)
 34     {
 35         printf("%c -> ", p->e);
 36         p = p->next;
 37     }
 38     printf("NULL\n");
 39     p = pHead;
 40     while(p != NULL)
 41     {
 42         if(p->sibling != NULL)
 43         {
 44             printf("%c -> ", p->e);
 45             printf("%c\t", p->sibling->e);
 46         }
 47         p = p->next;
 48     }
 49 }
 50 /***************************************************************************/
 51 void cloneNodes(ComplexList *pHead)
 52 {
 53     ComplexListNode *p = pHead;
 54     while(p != NULL)
 55     {
 56         ComplexListNode *newNode = new ComplexListNode;
 57         newNode->e = p->e + 32;
 58         newNode->next = p->next;
 59         newNode->sibling = NULL;
 60         p->next = newNode;
 61         p = newNode->next;
 62     }
 63 }
 64 
 65 void connectSibling(ComplexList *pHead)
 66 {
 67     ComplexListNode *pPre = pHead, *p;
 68     while(pPre != NULL && pPre->next != NULL)
 69     {
 70         p = pPre->next;
 71         if(pPre->sibling != NULL)
 72             p->sibling = pPre->sibling->next;
 73         pPre = p->next;
 74     }
 75 }
 76 
 77 ComplexList* getClonedComplexList(ComplexList *pHead)
 78 {
 79     ComplexListNode *pPre = pHead, *newHead = NULL, *p;
 80     while(pPre != NULL && pPre->next != NULL)
 81     {
 82         if(newHead != NULL) 
 83         {
 84             p->next = pPre->next;
 85             p = p->next;
 86         }
 87         else 
 88         {
 89             newHead = pPre->next;
 90             p = newHead;
 91         }
 92         pPre->next = pPre->next->next;
 93         pPre = pPre->next;
 94     }
 95     return newHead;
 96 }
 97 
 98 ComplexList* clone(ComplexList *pHead)
 99 {
100     cloneNodes(pHead);
101     connectSibling(pHead);
102     return getClonedComplexList(pHead);
103 }
104 
105 int main()
106 {
107     ComplexList *pHead = creatComplexList();
108     printf("original List.\n");
109     printComplexList(pHead);
110 
111     ComplexList *newHead = clone(pHead);
112     printf("cloned List.\n");
113     printComplexList(newHead);
114 
115     printf("original List.\n");
116     printComplexList(pHead);
117 
118     return 0;
119 }
View Code

程序说明:对一个结点,若 next 和 sibling 同时为 0,先保存 next 指针。
样例输入:AB AC BC BE CD DE DB(回车换行)

 

 27.二叉搜索树生成有序双向链表

  1 #include <iostream> 
  2 #include <string> 
  3 using namespace std; 
  4 typedef struct BTNode 
  5 { 
  6     int v;     // In this code, default positive Integer. 
  7     BTNode *pLeft; 
  8     BTNode *pRight; 
  9     BTNode(int x) : v(x), pLeft(NULL), pRight(NULL) {} 
 10 } DbList; 
 11 /********************************************************/
 12 /*****        Basic functions  for binary tree     ***********/
 13 BTNode* createBinaryTree() // input a preOrder sequence, 0 denote empty node.
 14 { 
 15     BTNode *pRoot = NULL;
 16     int r;
 17     cin >> r;
 18     if(r != 0)         // equal to if(!r) return;
 19     {
 20         pRoot = new BTNode(r);
 21         pRoot->pLeft = createBinaryTree();
 22         pRoot->pRight = createBinaryTree();
 23 
 24     }
 25     return pRoot;
 26 } 
 27 
 28 void printBinaryTree(BTNode *root, int level = 1){ 
 29     if(root == NULL) { cout << "NULL"; return; }; 
 30     string s; 
 31     for(int i = 0; i < level; ++i) s += "   "; 
 32     cout << root->v << endl << s; 
 33     printBinaryTree(root->pLeft, level+1); 
 34     cout << endl << s; 
 35     printBinaryTree(root->pRight, level+1); 
 36 } 
 37 
 38 // void releaseBinaryTree(BTNode *root){ 
 39 //     if(root == NULL) return; 
 40 //     releaseBinaryTree(root->pLeft); 
 41 //     releaseBinaryTree(root->pRight); 
 42 //     delete[] root; 
 43 //     root = NULL; 
 44 // } 
 45 /******************************************************************/
 46 /****************** basic function for double linked list. *******/
 47 void printDbList(DbList *pHead)
 48 {
 49     if(pHead == NULL) return;
 50     DbList *p = pHead;
 51     cout << "Print from left to right:" << endl;
 52     while(p->pRight != NULL) { cout << p->v << " "; p = p->pRight;}
 53     cout << p->v << endl;
 54 
 55     cout << "Print from left to right:" << endl;
 56     while(p != NULL) { printf("%-3d", p->v); p = p->pLeft;}
 57     cout << endl;
 58 }
 59 void releaseDbList(DbList *pHead)
 60 {
 61     if(pHead == NULL) return;
 62     releaseDbList(pHead->pRight);
 63     delete[] pHead;
 64 }
 65 /******************************************************************/
 66 /*****   binary search tree translate to double linked list    ******/
 67 void convert(BTNode *root, BTNode **tail)
 68 {
 69     if(root == NULL) return;
 70 
 71     if(root->pLeft != NULL)
 72         convert(root->pLeft, tail);
 73     root->pLeft = *tail;
 74     if(*tail) 
 75         (*tail)->pRight = root; 
 76     *tail = root; 
 77     
 78     if(root->pRight != NULL)
 79         convert(root->pRight, tail);
 80 };
 81 
 82 BTNode* treeToDList(BTNode *root)
 83 {
 84     if(root == NULL) return NULL;
 85     BTNode *tail = NULL;
 86     convert(root, &tail);
 87     BTNode *pHead = tail;
 88     while(pHead != NULL && pHead->pLeft != NULL)
 89         pHead = pHead->pLeft;
 90     return pHead;
 91 }
 92 
 93 int main(){ 
 94     int TestTime = 3, k = 1; 
 95     while(k <= TestTime) 
 96     { 
 97         cout << "Test " << k++ << ":" << endl; 
 98 
 99         cout << "Create a tree: " << endl; 
100         BTNode *pRoot = createBinaryTree(); 
101         printBinaryTree(pRoot); 
102         cout << endl; 
103 
104         DbList *DbListHead = treeToDList(pRoot); // pRoot translate to Double linked list.
105 
106         printDbList(DbListHead); 
107         cout << endl; 
108 
109         releaseDbList(DbListHead); 
110     } 
111     return 0; 
112 }
View Code

note: 按先序输入,0表示结束。
样例输入:

a. 10 6 4 0 0 8 0 0 14 12 0 0 16 00

b. 0 (生成空树)

c. 1

d. 2 1 0 0 3 0 0

 28.字符串的全排列

Go:  ( 3. 字符的排列组合 )

 相关例题:八皇后问题(可扩展为 n 皇后问题)

 题目:8 x 8国际象棋上,摆8 个皇后,求她们任两个不同行、不同列且不在同一对角线上的摆法个数。

#include <stdio.h>
int solutionNumber = 0;

void print(int data[], int length)
{
	for(int i = 0; i < length; ++i)
		printf("(%d, %d)  ", i+1, data[i]+1);
	printf("\n");
}
bool judge(int data[], int length)
{
	for(int i = 0; i < length; ++i)
	{
		for(int j = i +1; j < length; ++j)
		{
			if((j - i) == (data[j] - data[i]) || (j - i) == data[i] - data[j])
				return false; // not the solution
		}

	}
	return true;
}
void swap(int &a, int &b) // do not forget the reference.
{
	int tem = a;
	a = b;
	b = tem;
}

void permutation(int data[], int length, int begin)
{
	if(begin == length-1)
	{
		if(judge(data, length))
		{
		//	print(data, length);
			++solutionNumber;
		}
		return;
	}
	for(int start = begin; start < length; ++start)
	{
		swap(data[start], data[begin]);
		permutation(data, length, begin+1);
		swap(data[start], data[begin]);
	}
}

int main()
{
	int columnIndex[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};  /* 不在同行同列  */
	permutation(columnIndex, 8, 0);              /*  判断是否可以不在同一对角线  */
	printf("Number of Solution: %d\n", solutionNumber);
	return 0;
}

 

 

 

 

 

posted on 2014-04-30 15:51  进阶之路  阅读(423)  评论(0编辑  收藏  举报