程序员面试金典_2020_10_1

面试题 04.03. 特定深度节点链表

class Solution {
public:
    vector<ListNode*> listOfDepth(TreeNode* tree) {
    if(tree==NULL)
    return {};
    vector<ListNode*>res;
    ListNode*head=new ListNode(tree->val);
    res.push_back(head);
    queue<TreeNode*>dic;
    dic.push(tree);
    while(!dic.empty())
    {
        int l=dic.size();
        ListNode* p=new ListNode(0);
        ListNode* q=p;
        for(int i=0;i<l;i++)
        {
            auto top=dic.front();
            dic.pop();
            if(top->left)
            {
               p->next=new ListNode(top->left->val);
               dic.push(top->left);
               p=p->next;
            }
            if(top->right)
            {
                p->next=new ListNode(top->right->val);
                dic.push(top->right);
                p=p->next;
            }
        }
        if(q->next)
        {
            res.push_back(q->next);
        }
    }
    return res;
    }
};

面试题 04.04. 检查平衡性

class Solution {
public:
    bool isBalanced(TreeNode* root) {
    if(root==NULL) return true;
    return isBalanced(root->left)&&isBalanced(root->right)&&(abs(height(root->left) - height(root->right)) <= 1);
    }
    int height(TreeNode*root)
    {
        if(root==NULL) return 0;
        else return max(height(root->left)+1,height(root->right)+1);
    }
};

面试题 04.05. 合法二叉搜索树

class Solution {
public:
TreeNode*pre=NULL;
    bool isValidBST(TreeNode* root) {
    if(root==NULL) return true;
    if(!isValidBST(root->left)) return false;
    if(pre&&root->val<=pre->val) return false;
    pre=root;
    if(!isValidBST(root->right)) return false;
    return true;
    }
};

面试题 04.06. 后继者

class Solution {
public:
TreeNode*last=NULL;
    TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
    if(root==NULL) return NULL;
   TreeNode*left= inorderSuccessor(root->left,p);
    if(last==p&&left==NULL) return root;
    last=root;
    TreeNode*right=inorderSuccessor(root->right,p);
    return left==NULL?right==NULL?NULL:right:left;
    }
};

面试题 04.08. 首个共同祖先

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
   if(root==NULL||root==p||root==q) return root;
   TreeNode*left=lowestCommonAncestor(root->left,p,q);
   TreeNode*right=lowestCommonAncestor(root->right,p,q);
   if(left&&right) return root;
   if(left) return left;
   return right;
    }
};

你可能感兴趣的:(刷题)