1.有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。

给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500。

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/

class TreePrinter {
public:
    vector<vector<int> > printTree(TreeNode* root) {
        // write code here
        queue<TreeNode*> q;
        int val = -1;
        TreeNode* last =nullptr;
        TreeNode* nlast =nullptr;
         TreeNode* cur =nullptr;
        nlast  = root;
        q.push(root);
        vector<int>v;
       vector<vector<int>>ret;
        while(!q.empty()){
            cur = q.front();
            q.pop();
 
            int val = cur->val;
            v.push_back(val);
            
   
            if(cur->left){
                q.push(cur->left);
                last = cur->left;
            }
            if(cur->right){
                q.push(cur->right);
                last = cur->right;
            }
            if(nlast == cur){
                ret.push_back(v);
                v.clear();
                nlast = last;
            }
   
        }
        return ret;
        
        
    }
};

 

2.如果对于一个字符串A,将A的前面任意一部分挪到后边去形成的字符串称为A的旋转词。比如A="12345",A的旋转词有"12345","23451","34512","45123"和"51234"。对于两个字符串A和B,请判断A和B是否互为旋转词。

给定两个字符串AB及他们的长度lenalenb,请返回一个bool值,代表他们是否互为旋转词。

测试样例:
"cdab",4,"abcd",4
返回:true
直通BAT面试算法精讲课1
class Rotation {
public:
    bool chkRotation(string A, int lena, string B, int lenb) {
        // write code here
        if(lena!=lenb){
            return false; 
        }
         
        string C= A+A;
        for(int i=0;i<lena;i++){
            string D=C.substr(i,lena);
           
            if(D==B)
                return true;
        }
        return false;
             
    }
};
View Code

相关文章:

  • 2022-12-23
  • 2021-04-23
  • 2021-04-18
  • 2021-11-03
  • 2021-09-09
  • 2021-04-19
  • 2022-01-15
  • 2021-07-16
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-04-24
  • 2022-12-23
  • 2021-08-14
  • 2021-09-08
  • 2022-12-23
相关资源
相似解决方案