剑指offer —— 第4章解决面试题的思路 面试题 19 - 28

19.二叉树的镜像

操作给定的二叉树,将其变换为源二叉树的镜像。

二叉树的镜像定义:源二叉树 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11
    	镜像二叉树
    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5

思路:前序遍历,交换非叶子结点的左右子树结点

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    void Mirror(TreeNode *pRoot) {
        if(pRoot == nullptr) return;
        if(pRoot->left == nullptr && pRoot->right == nullptr) return;
        TreeNode *pTemp = pRoot->left;
        pRoot->left = pRoot->right;
        pRoot->right = pTemp;
        if(pRoot->left != nullptr) Mirror(pRoot->left);
        if(pRoot->right != nullptr) Mirror(pRoot->right);
    }
};

20.顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

思路:没仔细看原书方法,下面是LeetCode里的。非常直接的方法,定义上下左右边界,一旦超出边界就break。

class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        if(matrix.empty()) return {};
        int m = matrix.size(), n = matrix[0].size();
        vector<int> spiral(m * n);
        int u = 0, d = m - 1, l = 0, r = n - 1, k = 0;
        while(true){
            //up
            for(int col = l; col <= r; col++) spiral[k++] = matrix[u][col];
            if(++u > d) break;
            //right
            for(int row = u; row <= d; row++) spiral[k++] = matrix[row][r];
            if(--r < l) break;
            //down
            for(int col = r; col >= l; col--) spiral[k++] = matrix[d][col];
            if(--d < u) break;
            //left
            for(int row = d; row >= u; row--) spiral[k++] = matrix[row][l];
            if(++l > r) break; 
        }
        return spiral;
    }
};

21.包含min函数的栈

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

思路:利用辅助栈保存目前栈的最小元素

class Solution {
public:
    void push(int value) {
        stackInt.push(value);
        if(stackMin.empty()|| value < stackMin.top())
            stackMin.push(value);
        else
            stackMin.push(stackMin.top());
    }
    void pop() {
        if(!stackInt.empty() && !stackMin.empty())
        {
            stackInt.pop();
            stackMin.pop();
        }
            
    }
    int top() {
        return stackInt.top();
    }
    int min() {
        return stackMin.top();
    }
private:
    stack<int> stackInt;
    stack<int> stackMin;
};

22.栈的压入、弹出序列

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

思路:利用辅助栈,不断的压入入栈序列中的元素,一旦辅助栈栈顶元素等于出栈序列,辅助栈出栈。该问题中也可以用vector的back(), push_back(), pop_back()方法替代stack。

class Solution {
public:
    bool IsPopOrder(vector<int> pushV,vector<int> popV) {
        if(pushV.empty()) return false;
        stack<int> mStack;
        for(int i = 0, j = 0; i < pushV.size(); i++)
        {
            mStack.push(pushV[i]);
            while(j < popV.size() && mStack.top() == popV[j])
            {
                mStack.pop();
                j++;
            }
        }
        return mStack.empty();
    }
};

23.从上往下打印二叉树

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

思路:广度优先遍历,使用queue,将头结点放入队列,将头结点的值放入ret,出队列,并且将其左右结点放入队列。

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    vector<int> PrintFromTopToBottom(TreeNode* root) {
        vector<int> ret;
        if(!root) return ret;
        queue<TreeNode*> pQueue;
        pQueue.push(root);
        while(!pQueue.empty()){
            TreeNode* pNode = pQueue.front();
            pQueue.pop();
            ret.push_back(pNode->val);
            if(pNode->left) pQueue.push(pNode->left);
            if(pNode->right) pQueue.push(pNode->right);
        }
        return ret;
    }
};

24.二叉搜索树的后序遍历序列

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。

思路:

递归:序列的最后一个元素为根节点,左子树都比根节点小,遍历右子树时一旦有结点小于根节点返回false

class Solution {
public:
    bool VerifySquenceOfBST(vector<int> sequence) {
        return bst(sequence,0,sequence.size()-1);
    }
    bool bst(vector<int> sequence,int begin,int end){
        if(sequence.empty()||begin>end)
            return false;
        int root=sequence[end];
        int i=begin;
        for(;i<end;++i)
            if(sequence[i]>root)//i坐标为右子树第一个节点
                break;
        for(int j=i;j<end;++j)
            if(sequence[j]<root)
                return false;
        bool left=true;
        if(i>begin)
            left=bst(sequence,begin,i-1);
        bool right=true;
        if(i<end-1)
            right=bst(sequence,i,end-1);
        return left&&right;
    }
};

非递归:左子树与右子树的结点数等于length,一旦不是二叉搜索树结果将小于length。

class Solution {
public:
    bool VerifySquenceOfBST(vector<int> sequence) {
        if(sequence.empty()) return false;
        int pLength = sequence.size();
        int i = 0;
        while(--pLength)
        {
            while(i < pLength && sequence[i] < sequence[pLength]) i++;
            while(i < pLength && sequence[i] > sequence[pLength]) i++;
            if(i < pLength)
                return false;
            i = 0;
        }
        return true;
    }
};

25.二叉树中和为某一值的路径

输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前) 

思路:深度优先搜索,如果访问结点为叶子结点,并且值等于预期,就将path放入ret。如果不是叶子结点,递归调用函数访问其左右子树。

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        vector<vector<int>> ret;
        if(root == nullptr) return ret;
        vector<int> path;
        int currentNumber = 0;
        FindPath(root, expectNumber, path, currentNumber, ret);
        return ret;
    }
private:
    void FindPath
    (
        TreeNode* root, 
        int expectNumber, 
        vector<int> path, 
        int currentNumber,
        vector<vector<int>> &ret
    )
    {
        currentNumber += root->val;
        path.push_back(root->val);
        bool isLeaf = root->left == NULL && root->right == NULL;
        if(currentNumber == expectNumber && isLeaf)
            ret.push_back(path);
        if(root->left != NULL)
            FindPath(root->left, expectNumber, path, currentNumber, ret);
        if(root->right != NULL)
            FindPath(root->right, expectNumber, path, currentNumber, ret);
        path.pop_back();

    }
};

26.复杂链表的复制

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

思路:分三步解决问题,首先在每个结点的复制放在其后,然后对每个复制结点的随机指针赋值,最后将链表分为两个。

/*
struct RandomListNode {
    int label;
    struct RandomListNode *next, *random;
    RandomListNode(int x) :
            label(x), next(NULL), random(NULL) {
    }
};
*/
class Solution {
public:
    RandomListNode* Clone(RandomListNode* pHead)
    {
        CloneNodes(pHead);
        ConnectRandomNodes(pHead);
        return ReconnectNodes(pHead);
    }
private:
    void CloneNodes(RandomListNode* pHead)
    {
        RandomListNode* pNode = pHead;
        while(pNode != NULL)
        {
            RandomListNode* pCloned = new RandomListNode(pNode->label);
            pCloned->next = pNode->next;
            pNode->next = pCloned;
            pNode = pCloned->next;
        }
    }
    void ConnectRandomNodes(RandomListNode* pHead)
    {
        RandomListNode* pNode = pHead;
        while(pNode != NULL){
            RandomListNode* pCloned = pNode->next;
            if(pNode->random != NULL)
                pCloned->random = pNode->random->next;
            pNode = pCloned->next;
        }
    }
    RandomListNode* ReconnectNodes(RandomListNode* pHead)
    {
        RandomListNode* pNode = pHead;
        RandomListNode* pClonedHead = NULL;
        RandomListNode* pClonedNode = NULL;
        if(pNode != NULL)
        {
            pClonedHead = pClonedNode = pNode->next;
            pNode->next = pClonedNode->next;
            pNode = pNode->next;
        }
        while(pNode != NULL)
        {
            pClonedNode->next = pNode->next;
            pClonedNode = pClonedNode->next;
            pNode->next = pClonedNode->next;
            pNode = pNode->next;
        }
        return pClonedHead;
    }
};

27.二叉搜索树与双向链表

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

思路:二叉搜索树的中序遍历即为双向链表的顺序。

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    TreeNode* Convert(TreeNode* pRootOfTree)
    {
        TreeNode *pLastNodeInList = nullptr;
        ConvertNode(pRootOfTree, &pLastNodeInList);
        TreeNode *pHeadOfList = pLastNodeInList;
        while(pHeadOfList != nullptr && pHeadOfList->left != nullptr)
            pHeadOfList = pHeadOfList->left;
        return pHeadOfList;
    }
    void ConvertNode(TreeNode *pNode, TreeNode **pLastNodeInList)
    {
        if(pNode == nullptr) return;
        TreeNode *pCurrent = pNode;
        if(pCurrent->left != nullptr)
            ConvertNode(pCurrent->left, pLastNodeInList);
        pCurrent->left = *pLastNodeInList;
        if(*pLastNodeInList != nullptr)
            (*pLastNodeInList)->right = pCurrent;
        *pLastNodeInList = pCurrent;
        if(pCurrent->right != nullptr)
            ConvertNode(pCurrent->right, pLastNodeInList);
    }
};

28.字符串的排列

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

思路:首先固定第一位,然后将第一位与后面的交换,以此类推。这个题目跟原书不一样,有重复的字符并且要求字典序。

class Solution {
public:
    vector<string> Permutation(string str) {
        vector<string> ret;
        return Permutation(str, 0, ret);
    }
private:
    vector<string> Permutation(string &str, int pBegin, vector<string> &ret){
        int pSize = str.size();
        if(pBegin == pSize - 1)
        {
            ret.push_back(str);
        }
        else
        {
            for(int i = pBegin; i < pSize; i++){
                if (i != pBegin && str[pBegin] == str[i]){
                    continue;
                }
                char tmp = str[pBegin];
                str[pBegin] = str[i];
                str[i] = tmp;
                Permutation(str, pBegin + 1, ret);
                tmp = str[pBegin];
                str[pBegin] = str[i];
                str[i] = tmp;
           }
        }
        sort(ret.begin(), ret.end());
        return ret;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值