分享
来源:互联网 发布:龙之谷cpu优化补丁 编辑:程序博客网 时间:2024/05/14 01:59
二叉树两个节点的最近公共父节点
template <class T>struct TreeNode{ TreeNode(const T& value = T()) :_data(value) , _left(0) , _right(0) {} T _data;//节点的值 TreeNode<T>* _left;//左孩子 TreeNode<T>*_right;//右孩子};//利用后序遍历Node* getLastCommAncestor(Node * root,Node * n1,Node *n2){ if (root == NULL){ return NULL; } if (n1 == root ||n2 == root){ return root; } Node *left = NULL; Node *right = NULL; left = getCommonPa(root->_left, n1, n2); right = getCommonPa(root->_right, n1, n2); if (left == NULL){ return right; } if (right == NULL){ return left; } return root; } Node* getRoot() { return _root; }void TestBinaryTree(){ int arr[] = { 1, 2, 3, '#', '#', 4, '#', '#', 5, 6 }; size_t size = sizeof(arr) / sizeof(arr[0]); BinaryTree<int> bt(arr, size, '#'); TreeNode<int>* node1 = bt.getRoot()->_left->_left; TreeNode<int>* node2 = bt.getRoot()->_left->_right; TreeNode<int>* anc = bt.getLastCommAncestor(bt.getRoot(), node1, node2); if (anc) cout << anc->_data << endl; else cout << "没有公共祖先" << endl;}
实现一个栈,要求实现Push(出栈)、Pop(入栈)、Min(返回最小值的操作) 的时间复杂度为O(1)
template <class T>class StackMin{public: void Push(T data)//入栈 { s.push(data); //min为空或min中的最小值>=data,将data入栈到min if (min.empty() || data <= min.top()) { min.push(data); } } void Pop()//出栈 { if (s.empty()) return; //如果要删除的数据为最小数,则要同时将min中的最小数也删除,否则只需删除s的数据 if (s.top() == min.top()) { min.pop(); } s.pop(); } T Min()//获取栈中的最小值(时间复杂度:O(1)) { if (!min.empty()) return min.top();//min的栈顶元素即为最小值 } void print() { while (!s.empty()) { cout << s.top() << "->"; s.pop(); } cout << endl; while (!min.empty()) { cout << min.top() << "->"; min.pop(); } cout << endl; }protected: stack<T> s; //普通栈 stack<T> min;//存最小的数};void TestStackMin(){ StackMin<int> s; s.Push(4); s.Push(3); s.Push(5); s.Push(1); s.Push(1); s.Push(2); s.print(); s.Pop(); s.Pop(); s.print(); }
阅读全文
0 0
- 分享
- 分享
- 分享。。。。
- 分享
- 分享
- 分享
- 分享
- 分享
- 分享
- 分享
- 分享
- 分享
- 分享
- 分享
- 分享
- 分享
- 分享
- 分享
- Java NIO浅析(转)
- spring
- Palindrome Linked List
- 关于数据库更新字段,对更新时间的设置
- [期望DP+高斯消元] BZOJ3143: [Hnoi2013]游走
- 分享
- Spring MVC 与 Struts2
- java 群发求职邮件
- route 3
- BZOJ3036-绿豆蛙的归宿-概率与期望-DP
- 记录:自定义类似RatingBar效果
- 第22章 傅里叶变换性质
- Android设置EditText为单行 (软键盘显示下一项)
- SpringBoot--transaction