分享

来源:互联网 发布:龙之谷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();    }
原创粉丝点击