Chap4: question: 19 - 28
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. 顺时针打印矩阵
- #include <stdio.h>
- void printMatrix(int (*A)[], int rows, int columns)
- {
- if(rows < || columns < ) return;
- int r1, r2, c1, c2;
- r1 = c1 = , r2 = rows-, c2 = columns-;
- while(r1 <= r2 && c1 <= c2) /* 打印结束时, r1 = r2+1, c1 = c2+1; */
- {
- for(int i = c1; i <= c2 && r1 <= r2; ++i)
- printf("%d ", A[r1][i]);
- ++r1;
- for(int i = r1; c1 <= c2 && i <= r2; ++i)
- printf("%d ", A[i][c2]); /* 要保证 c1 <= c2 */
- --c2;
- for(int i = c2; i >= c1 && r1 <= r2; --i)
- printf("%d ", A[r2][i]);
- --r2;
- for(int i = r2; i >= r1 && c1 <= c2; --i)
- printf("%d ", A[i][c1]);
- ++c1;
- }
- printf("\n");
- }
- int main()
- {
- int test1[][] = {{, , },
- {, , },
- {, , }};
- printMatrix(test1, , );
- int test2[][] = {, , };
- printMatrix(test2, , );
- /* // first set int (*A)[1], then began called below.
- int test3[3][1] = {{1}, {2}, {3}};
- printMatrix(test3, 3, 1);
- int test4[1][1] = {1};
- printMatrix(test4, 1, 1);
- */
- return ;
- }
(
)
21. 包含 min 函数的栈
要求调用 min,pop,push,时间复杂度都是 O(1)。
- #include <iostream>
- #include <stack>
- #include <cassert>
- #include <string>
- template<typename T> class Stack
- {
- public:
- void push(T value);
- void pop();
- T min();
- private:
- std::stack<T> data;
- std::stack<T> minData;
- };
- template<typename T> void Stack<T>::push(T value)
- {
- data.push(value);
- if(minData.empty() || minData.top() >= value)
- minData.push(value);
- else
- minData.push(minData.top());
- }
- template<typename T> void Stack<T>::pop()
- {
- assert(data.size() > && minData.size() > );
- data.pop();
- minData.pop();
- }
- template<typename T> T Stack<T>::min()
- {
- return minData.top();
- }
- int main()
- {
- Stack<char> st;
- std::string numbers;
- while(std::cin >> numbers)
- {
- for(size_t i = ; i < numbers.length(); ++i) st.push(numbers[i]);
- for(size_t i = ; i < numbers.length(); ++i)
- {
- std::cout << "st.min(): " << st.min() << std::endl;
- st.pop();
- }
- }
- return ;
- }
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} ,可画出一颗二叉搜索树。
- #include <iostream>
- /* verify the seq which should be the postOrder of a Binary Search Tree */
- bool postOrderOfBST(int sequence[], int len)
- {
- if(sequence == NULL || len == ) return false;
- bool answer = false;
- int root = sequence[len-]; /* value of root node */
- int leftLength = ;
- for(; leftLength < len-; ++leftLength)
- {
- if(sequence[leftLength] > root) break;
- }
- /* verify right-subtree, should big than root */
- for(int i = leftLength + ; i < len -; ++i)
- {
- if(sequence[i] < root) return false;
- }
- int rightLength = len - - leftLength;
- bool left = true, right = true;
- if(leftLength > )
- bool left = postOrderOfBST(sequence, leftLength);
- if(rightLength)
- bool right = postOrderOfBST(sequence+leftLength, rightLength);
- return (left && right);
- }
- void printResult(bool v)
- {
- std::cout << "Is LRD of a BFS? " ;
- if(v) std::cout << "true" << std::endl;
- else std::cout << "false" << std::endl;
- }
- int main()
- {
- std::cout << "Test 1: ";
- int test1[] = {, , , , , , , , };
- printResult(postOrderOfBST(test1, sizeof(test1) / )) ;
- std::cout << "Test 2: ";
- int test2[] = {, , };
- printResult(postOrderOfBST(test2, sizeof(test2) / ));
- std::cout << "Test 3: ";
- int test3[] = {};
- printResult(postOrderOfBST(test3, sizeof(test3) / ));
- return ;
- }
25. 二叉树中和为某一值的路径(递归)
- #include <iostream>
- #include <string>
- #include <vector>
- 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 != )
- pRoot->pLeft = createBinaryTree(u);
- if(v != )
- 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 = ){
- if(root == NULL) { cout << "NULL"; return; };
- string s;
- for(int i = ; i < level; ++i) s += "\t";
- cout << root->v << endl << s;
- print(root->pLeft, level+);
- cout << endl << s;
- print(root->pRight, level+);
- }
- /******************************************************************/
- void findPath(BTNode *root, int target, vector<int>& path, int curSum)
- {
- if(root == NULL) return;
- curSum += root->v;
- path.push_back(root->v);
- if(!root->pLeft && !root->pRight && (curSum == target)) // root node is a leaf, get a path.
- {
- for(auto it = path.begin(); it != path.end(); ++it)
- cout << *it << " ";
- cout << endl;
- }
- findPath(root->pLeft, target, path, curSum);
- findPath(root->pRight, target, path, curSum);
- path.pop_back();
- }
- void findPath(BTNode *root, int target)
- {
- if(root == NULL) return;
- vector<int> path;
- findPath(root, target, path, );
- }
- int main(){
- int TestTime = , k = ;
- while(k <= TestTime)
- {
- int root;
- cout << "Test " << k++ << ":" << endl;
- cout << "Create a tree: " << endl;
- cin >> root;
- BTNode *pRoot = createBinaryTree(root);
- print(pRoot);
- cout << endl;
- cout << "target : 22" << endl << "findPath :" << endl;
- findPath(pRoot, );
- release(pRoot);
- }
- return ;
- }
Code
26. 复杂链表的复制
- #include <stdio.h>
- typedef char Elem;
- typedef struct ComplexListNode
- {
- Elem e;
- ComplexListNode *next;
- ComplexListNode *sibling;
- } ComplexList;
- ComplexListNode Node[] = {};
- /***************************************************************/
- ComplexList* creatComplexList()
- {
- for(int i = ; i < ; ++i)
- Node[i].e = i + 'A';
- char u, v;
- while((scanf("%c%c", &u, &v) == ) )
- {
- if(u >= 'A' && u <= 'Z' && v >= 'A' && v <= 'Z')
- {
- if(Node[u-'A'].next == NULL)
- Node[u-'A'].next = &Node[v-'A'];
- else if(Node[u-'A'].sibling == NULL)
- Node[u-'A'].sibling = &Node[v-'A'];
- }
- if(getchar() == '\n') break;
- }
- return &Node[];
- }
- void printComplexList(ComplexList *pHead)
- {
- ComplexListNode *p = pHead;
- while(p != NULL)
- {
- printf("%c -> ", p->e);
- p = p->next;
- }
- printf("NULL\n");
- p = pHead;
- while(p != NULL)
- {
- if(p->sibling != NULL)
- {
- printf("%c -> ", p->e);
- printf("%c\t", p->sibling->e);
- }
- p = p->next;
- }
- }
- /***************************************************************************/
- void cloneNodes(ComplexList *pHead)
- {
- ComplexListNode *p = pHead;
- while(p != NULL)
- {
- ComplexListNode *newNode = new ComplexListNode;
- newNode->e = p->e + ;
- newNode->next = p->next;
- newNode->sibling = NULL;
- p->next = newNode;
- p = newNode->next;
- }
- }
- void connectSibling(ComplexList *pHead)
- {
- ComplexListNode *pPre = pHead, *p;
- while(pPre != NULL && pPre->next != NULL)
- {
- p = pPre->next;
- if(pPre->sibling != NULL)
- p->sibling = pPre->sibling->next;
- pPre = p->next;
- }
- }
- ComplexList* getClonedComplexList(ComplexList *pHead)
- {
- ComplexListNode *pPre = pHead, *newHead = NULL, *p;
- while(pPre != NULL && pPre->next != NULL)
- {
- if(newHead != NULL)
- {
- p->next = pPre->next;
- p = p->next;
- }
- else
- {
- newHead = pPre->next;
- p = newHead;
- }
- pPre->next = pPre->next->next;
- pPre = pPre->next;
- }
- return newHead;
- }
- ComplexList* clone(ComplexList *pHead)
- {
- cloneNodes(pHead);
- connectSibling(pHead);
- return getClonedComplexList(pHead);
- }
- int main()
- {
- ComplexList *pHead = creatComplexList();
- printf("original List.\n");
- printComplexList(pHead);
- ComplexList *newHead = clone(pHead);
- printf("cloned List.\n");
- printComplexList(newHead);
- printf("original List.\n");
- printComplexList(pHead);
- return ;
- }
程序说明:对一个结点,若 next 和 sibling 同时为 0,先保存 next 指针。
样例输入:AB AC BC BE CD DE DB(回车换行)
27.二叉搜索树生成有序双向链表
- #include <iostream>
- #include <string>
- using namespace std;
- typedef struct BTNode
- {
- int v; // In this code, default positive Integer.
- BTNode *pLeft;
- BTNode *pRight;
- BTNode(int x) : v(x), pLeft(NULL), pRight(NULL) {}
- } DbList;
- /********************************************************/
- /***** Basic functions for binary tree ***********/
- BTNode* createBinaryTree() // input a preOrder sequence, 0 denote empty node.
- {
- BTNode *pRoot = NULL;
- int r;
- cin >> r;
- if(r != ) // equal to if(!r) return;
- {
- pRoot = new BTNode(r);
- pRoot->pLeft = createBinaryTree();
- pRoot->pRight = createBinaryTree();
- }
- return pRoot;
- }
- void printBinaryTree(BTNode *root, int level = ){
- if(root == NULL) { cout << "NULL"; return; };
- string s;
- for(int i = ; i < level; ++i) s += " ";
- cout << root->v << endl << s;
- printBinaryTree(root->pLeft, level+);
- cout << endl << s;
- printBinaryTree(root->pRight, level+);
- }
- // void releaseBinaryTree(BTNode *root){
- // if(root == NULL) return;
- // releaseBinaryTree(root->pLeft);
- // releaseBinaryTree(root->pRight);
- // delete[] root;
- // root = NULL;
- // }
- /******************************************************************/
- /****************** basic function for double linked list. *******/
- void printDbList(DbList *pHead)
- {
- if(pHead == NULL) return;
- DbList *p = pHead;
- cout << "Print from left to right:" << endl;
- while(p->pRight != NULL) { cout << p->v << " "; p = p->pRight;}
- cout << p->v << endl;
- cout << "Print from left to right:" << endl;
- while(p != NULL) { printf("%-3d", p->v); p = p->pLeft;}
- cout << endl;
- }
- void releaseDbList(DbList *pHead)
- {
- if(pHead == NULL) return;
- releaseDbList(pHead->pRight);
- delete[] pHead;
- }
- /******************************************************************/
- /***** binary search tree translate to double linked list ******/
- void convert(BTNode *root, BTNode **tail)
- {
- if(root == NULL) return;
- if(root->pLeft != NULL)
- convert(root->pLeft, tail);
- root->pLeft = *tail;
- if(*tail)
- (*tail)->pRight = root;
- *tail = root;
- if(root->pRight != NULL)
- convert(root->pRight, tail);
- };
- BTNode* treeToDList(BTNode *root)
- {
- if(root == NULL) return NULL;
- BTNode *tail = NULL;
- convert(root, &tail);
- BTNode *pHead = tail;
- while(pHead != NULL && pHead->pLeft != NULL)
- pHead = pHead->pLeft;
- return pHead;
- }
- int main(){
- int TestTime = , k = ;
- while(k <= TestTime)
- {
- cout << "Test " << k++ << ":" << endl;
- cout << "Create a tree: " << endl;
- BTNode *pRoot = createBinaryTree();
- printBinaryTree(pRoot);
- cout << endl;
- DbList *DbListHead = treeToDList(pRoot); // pRoot translate to Double linked list.
- printDbList(DbListHead);
- cout << endl;
- releaseDbList(DbListHead);
- }
- return ;
- }
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;
- }
Chap4: question: 19 - 28的更多相关文章
- ubuntu下设置jupyter notebook 2017年07月29日 19:28:34 小旋锋 阅读数:8329 标签: ubuntu 更多 个人分类: python 二三事 来源:http://blog.csdn.net/suzyu12345/article/details/51037905 Ipython Notebook现在已经改名为Ipython jupyter,是最知名最好用的
ubuntu下设置jupyter notebook 来源:http://blog.csdn.net/suzyu12345/article/details/51037905 Ipython No ...
- 根据pid获得路径 2006-10-25 19:28
这是编写kill process时用到的 BOOL GetProcessModule(DWORD dwPID, DWORD dwModuleID, LPMODULEENTRY32 lpMe32, DW ...
- JavaSE_ IO流 总目录(19~22)
JavaSE学习总结第19天_IO流119.01 集合的特点和数据结构总结19.02 如何选择使用哪种集合19.03 集合常见功能和遍历方式总结19.04 异常的概述和分类19.05 JVM默认处理异 ...
- JavaSE学习总结第19天_IO流1
19.01 集合的特点和数据结构总结 HashSet.HashMap.Hashtable判断元素唯一性的方式: 通过对象的hashCode和equals方法来完成元素唯一性 如果对象的hashC ...
- 1Z0-050
QUESTION 13 View the Exhibit.Examine the following command that is executed for the TRANSPORT table ...
- A.Kaw矩阵代数初步学习笔记 5. System of Equations
“矩阵代数初步”(Introduction to MATRIX ALGEBRA)课程由Prof. A.K.Kaw(University of South Florida)设计并讲授. PDF格式学习笔 ...
- .NET运用AJAX 总结及其实例
1.AJAX简介 (1.没有AJAX会怎么样?普通的ASP.Net每次执行服务端方法的时候都要刷新当前页面,比如实现显示服务器的时间.每次都要刷新页面的坏处:页面刷新打断用户操作.速度慢.增加服务器的 ...
- 转:switch内部的变量定义问题(goto类似)
自我总结:(之前查过goto和switch的资料但是一直没有搞懂,直到今天看到这个讨论才懂了) 1 int a; 是个描述,而不是个命令,只是说明我需要空间,编译器会保证在相应的作用域之中这 ...
- HTML+CSS+JAVASCRIPT 总结
1. HTML 1: <!doctype html> 2: <!-- This is a test html for html, css, javascript --> 3: ...
随机推荐
- hdu 4642 Fliping game
http://acm.hdu.edu.cn/showproblem.php?pid=4642 对于给定的矩阵 操作步数的奇偶性是确定的 奇数步Alice赢 否则Bob赢 从左上角向右下角遍历遇到1就进 ...
- 【58测试】【贪心】【离散】【搜索】【LIS】【dp】
第一题 大天使之剑 大意: 有n个怪,每个怪的ph 为 h[i],有三种攻击方式,普通攻击:一次打一个怪一滴血:重击(消耗1魔法值):一次打一个怪两滴血:群体攻击(消耗1魔法值):一次打所有怪一滴血. ...
- IIS+PHP配置一次成功无错误版
1.首先去PHP官网下载php的压缩包(.zip),由于web服务器是IIS所以尽量使用线程不安全版本的,我下载的是: VC11 x86 Non Thread Safe (2015-May-14 18 ...
- SAP 增强-出口选找方法-全部
■ SAP 中如何寻找增强 方法一:利用TCODE寻找增强(第二代的增强) 执行一个程序(源代码后附),在选择屏幕处输入你所需要增强的程序TCODE,执行後,就会出现一个列表,那里就有关于如何增强这个 ...
- Term_Application
1 CRM(Customer Relationship Management)客户关系管理: (对ERP下游管理不足的补充) 是一个获取.保持和增加可获利客户的方法和过程. 市场营销.销售管理.客户关 ...
- Mongodb在NUMA机器上的优化
10gen在mongodb的部署指南上,提到了在NUMA机器上,mongodb可能会出现问题,参见:http://docs.mongodb.org/manual/administration/prod ...
- Filco minila 的蛋疼。
3494左shift坏了,期间邮寄厂家维修,就把尘封多年的minila拿出来用着. 最为人诟病的问题:蓝亚适配,与mac跟iphone都能快速的匹配连接上.但是对于我的dell vestro 2012 ...
- cocos2d项目 打包apk 项目名称相关设置
修改android项目名称(打包生成的默认apk名称),直接找到proj.android目录下.project文件夹里面比较靠前的xml配置,修改<name>项目名称</name&g ...
- 用javaScript实现 登陆记住密码功能。
一.先写一个存取 cookie的方法. function getCookie(cookiename) { var result; var mycookie = document.cookie; var ...
- 设置Android studio黑色主题
设置: 如上图,点击[Theme]下拉选项,选中[Darcula]主题,点击[Apply]应用修改,弹出重启Android Studio生效修改.如图: