• 面试经典150题 -- 二叉树 (总结)


    总的地址 : 

    面试经典 150 题 - 学习计划 - 力扣(LeetCode)全球极客挚爱的技术成长平台

    104 . 二叉树的最大深度

    104 . 二叉树的最大深度

    递归 : 

    直接用递归访问 , 访问左孩子 和 右孩子 , 如果 存在 , 深度就+1 ;

    1. class Solution {
    2. public int maxDepth(TreeNode root) {
    3. if(root == null) return 0 ;
    4. int lm = maxDepth(root.left) ;
    5. int rm = maxDepth(root.right) ;;
    6. return Math.max(lm, rm) + 1 ;
    7. }
    8. }

    层序遍历

    找到一层 就 ans ++ ;

    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
    8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10. * };
    11. */
    12. class Solution {
    13. public:
    14. int maxDepth(TreeNode* root) {
    15. int ans = 0;
    16. queue<TreeNode*> que;
    17. if(root != nullptr) que.push(root);
    18. while(!que.empty()){
    19. int size = que.size();
    20. ans ++;
    21. for(int i=0;i<size;i++){
    22. TreeNode* node = que.front();
    23. que.pop();
    24. if(node->left) que.push(node->left);
    25. if(node->right) que.push(node->right);
    26. }
    27. }
    28. return ans;
    29. }
    30. };

    100 . 相同的树

    链接 : 

    力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

    LeetCode题解链接 : 

    力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

    [迭代]

    > 采用广度优先遍历,用队列先存入两个树的头节点,每次判断队尾的两个结点是不是满足相等,不相等直接返回false,同时为空,继续下一对结点的判断 ;

    都不为空且值相等,就依次将两个节点的左孩子 和 右孩子 存入队列中;然后开始下一次的判断 ; 知道两个队列都为空为止 ;

    Java :

    1. class Solution {
    2.     public boolean isSameTree(TreeNode p, TreeNode q) {
    3.         if(p==null && q==null) return true;
    4.         if(p==null || q==null) return false;
    5.         if(p.val !=q.val) return false;
    6.         Queue<TreeNode> qp = new LinkedList<TreeNode>();
    7.         Queue<TreeNode> qq = new LinkedList<TreeNode>();
    8.         qp.offer(p);
    9.         qq.offer(q);
    10.         while(!qp.isEmpty() && !qq.isEmpty()){
    11.             TreeNode cp = qp.poll();
    12.             TreeNode cq = qq.poll();
    13.             if(cp==null&& cq==null) continue;
    14.             if((cp==null || cq==null) || cp.val != cq.val) return false;
    15.             qp.offer(cp.left) ;
    16.             qq.offer(cq.left) ;
    17.             qp.offer(cp.right) ;
    18.             qq.offer(cq.right) ;
    19.         }
    20.         return true ;
    21.     }
    22. }

    cpp 

    1. class Solution {
    2. public:
    3.     bool isSameTree(TreeNode* p, TreeNode* q) {
    4.         if(p==nullptr && q==nullptr) return true;
    5.         if(p==nullptr || q==nullptr) return false;
    6.         if(p->val !=q->val) return false;
    7.         queue<TreeNode*> qp ;
    8.         queue<TreeNode*> qq;
    9.         qp.push(p);
    10.         qq.push(q);
    11.         while(!qp.empty() && !qq.empty()){
    12.             TreeNode* cp = qp.front() ; qp.pop();
    13.             TreeNode* cq = qq.front() ; qq.pop();
    14.             if(cp==nullptr && cq==nullptr) continue;
    15.             if((cp==nullptr || cq==nullptr) || cp->val != cq->val) return false;
    16.             qp.push(cp->left) ;
    17.             qq.push(cq->left) ;
    18.             qp.push(cp->right) ;
    19.             qq.push(cq->right) ;
    20.         }
    21.         return true ;
    22.     }
    23. };

    [递归]

    > 用递归的思想实现上面迭代的过程,先判断两个根节点是否满足题意,满足就同时递归判断两个节点的左子树和右子树 ;

    Java 

    1. class Solution {
    2.     public boolean isSameTree(TreeNode p, TreeNode q) {
    3.         if(p==null && q==null) return true;
    4.         if(p==null || q==null) return false;
    5.         if(p.val != q.val) return false;
    6.         return isSameTree(p.left,q.left) && isSameTree(p.right,q.right) ;
    7.     }
    8. }

    cpp 

    1. class Solution {
    2. public:
    3.     bool isSameTree(TreeNode* p, TreeNode* q) {
    4.         if(p==nullptr && q==nullptr) return true;
    5.         else if(p==nullptr || q==nullptr) return false;
    6.         else if(p->val != q->val) return false;
    7.         else return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
    8.     }
    9. };

    226 . 反转二叉树

    链接

    226 . 反转二叉树

    递归 : 

    遍历一个结点就继续向下反转其左子树 和 右子树 ;

    1. class Solution {
    2. public:
    3. TreeNode* invertTree(TreeNode* root) {
    4. if(root == nullptr) return root ;
    5. swap(root->left,root->right);
    6. invertTree(root->left) ;
    7. invertTree(root->right) ;
    8. return root ;
    9. }
    10. };

    前序遍历

    按照中左右的顺序,先处理中间结点(交换其左右子树),然后将其左子树和右子树加入栈中 ;

    1. class Solution {
    2. public:
    3. TreeNode* invertTree(TreeNode* root) {
    4. if (root == NULL) return root;
    5. stack<TreeNode*> st;
    6. st.push(root);
    7. while(!st.empty()) {
    8. TreeNode* node = st.top(); //
    9. st.pop();
    10. swap(node->left, node->right);
    11. if(node->right) st.push(node->right); //
    12. if(node->left) st.push(node->left); //
    13. }
    14. return root;
    15. }
    16. };

    层序遍历

    和前序遍历类似,采用队列queue存放结点 ;

    广度优先,在遍历的过程中将每一层的每一个结点的左右孩子结点交换即可;

    1. class Solution {
    2. public:
    3. TreeNode* invertTree(TreeNode* root) {
    4. queue<TreeNode*> que;
    5. if (root != NULL) que.push(root);
    6. while (!que.empty()) {
    7. int size = que.size();
    8. for (int i = 0; i < size; i++) {
    9. TreeNode* node = que.front();
    10. que.pop();
    11. swap(node->left, node->right); // 节点处理
    12. if (node->left) que.push(node->left);
    13. if (node->right) que.push(node->right);
    14. }
    15. }
    16. return root;
    17. }
    18. };

    101 . 对称二叉树

    递归

    对于二叉树是否对称,要比较的是根节点的左子树与右子树是不是相互翻转的,理解这一点就知道了其实我们要比较的是两个树(这两个树是根节点的左右子树),所以在递归遍历的过程中,也是要同时遍历两棵树。

    我们要通过递归函数的返回值来判断两个子树的内侧节点和外侧节点是否相等。(遍历顺序 : 左右中 / 右左中 , "后序遍历 ")

    1. class Solution {
    2. public:
    3. bool cmp(TreeNode* left,TreeNode* right){
    4. if(left==nullptr && right!=nullptr) return false;
    5. else if(left!=nullptr && right==nullptr) return false;
    6. else if(left==nullptr && right==nullptr) return true;
    7. else if(left->val != right->val) return false;
    8. else return cmp(left->left,right->right) && cmp(left->right,right->left);
    9. }
    10. bool isSymmetric(TreeNode* root) {
    11. if(root == nullptr) return true;
    12. return cmp(root->left,root->right);
    13. }
    14. };

    迭代

    也就是用类似层序遍历的方式来实现递归的步骤 ;

    详细请看代码 : 

    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
    8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10. * };
    11. */
    12. class Solution {
    13. public:
    14. bool isSymmetric(TreeNode* root) {
    15. if(root == nullptr) return true;
    16. queue<TreeNode*> que;
    17. que.push(root->left);
    18. que.push(root->right);
    19. while(!que.empty()){
    20. TreeNode* l = que.front();
    21. que.pop();
    22. TreeNode* r = que.front();
    23. que.pop();
    24. if(!l && !r) continue;//左右结点均为空,直接下一步;
    25. if((l&&!r) || (!l&&r)) return false;//左右结点一个为空,返回false;
    26. if(l->val != r->val) return false;//均不为空但不相等,直接返回false;
    27. que.push(l->left);
    28. que.push(r->right);
    29. que.push(l->right);
    30. que.push(r->left);
    31. }
    32. return true;
    33. }
    34. };

    105. 从前序与中序遍历序列构造二叉树

    详细请看代码 : 

    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
    8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10. * };
    11. */
    12. class Solution {
    13. public:
    14. TreeNode* traversal(vector<int>& preorder,vector<int>& inorder){
    15. if(preorder.size() == 0) return nullptr;
    16. int num = preorder[0];
    17. TreeNode* root = new TreeNode(num);
    18. // 叶子节点
    19. if(preorder.size() == 1) return root;
    20. // 找到切割下标
    21. int splitIndex;
    22. for(splitIndex=0;splitIndex<inorder.size();splitIndex++){
    23. if(inorder[splitIndex] == num)
    24. break;
    25. }
    26. //切割中序数组
    27. vector<int> leftVecI(inorder.begin(),inorder.begin()+splitIndex);
    28. vector<int> rightVecI(inorder.begin()+splitIndex+1,inorder.end());
    29. // 去掉前序数组中的第一个元素
    30. preorder.erase(preorder.begin());
    31. // 切割前序数组
    32. vector<int> leftVecP(preorder.begin(),preorder.begin()+leftVecI.size());
    33. vector<int> rightVecP(preorder.begin()+leftVecI.size(),preorder.end());
    34. root->left = traversal(leftVecP,leftVecI);
    35. root->right = traversal(rightVecP,rightVecI);
    36. return root;
    37. }
    38. TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
    39. if(!preorder.size() || !inorder.size()) return nullptr;
    40. return traversal(preorder,inorder);
    41. }
    42. };

    106. 从中序与后序遍历序列构造二叉树

    详细请看代码 : 

    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
    8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10. * };
    11. */
    12. class Solution {
    13. private:
    14. // 中序区间:[inorderBegin, inorderEnd),后序区间[postorderBegin, postorderEnd)
    15. TreeNode* traversal (vector<int>& inorder, int inorderBegin, int inorderEnd, vector<int>& postorder, int postorderBegin, int postorderEnd) {
    16. if (postorderBegin == postorderEnd) return NULL;
    17. int rootValue = postorder[postorderEnd - 1];
    18. TreeNode* root = new TreeNode(rootValue);
    19. if (postorderEnd - postorderBegin == 1) return root;
    20. int delimiterIndex;
    21. for (delimiterIndex = inorderBegin; delimiterIndex < inorderEnd; delimiterIndex++) {
    22. if (inorder[delimiterIndex] == rootValue) break;
    23. }
    24. // 切割中序数组
    25. // 左中序区间,左闭右开[leftInorderBegin, leftInorderEnd)
    26. int leftInorderBegin = inorderBegin;
    27. int leftInorderEnd = delimiterIndex;
    28. // 右中序区间,左闭右开[rightInorderBegin, rightInorderEnd)
    29. int rightInorderBegin = delimiterIndex + 1;
    30. int rightInorderEnd = inorderEnd;
    31. // 切割后序数组
    32. // 左后序区间,左闭右开[leftPostorderBegin, leftPostorderEnd)
    33. int leftPostorderBegin = postorderBegin;
    34. int leftPostorderEnd = postorderBegin + delimiterIndex - inorderBegin; // 终止位置是 需要加上 中序区间的大小size
    35. // 右后序区间,左闭右开[rightPostorderBegin, rightPostorderEnd)
    36. int rightPostorderBegin = postorderBegin + (delimiterIndex - inorderBegin);
    37. int rightPostorderEnd = postorderEnd - 1; // 排除最后一个元素,已经作为节点了
    38. root->left = traversal(inorder, leftInorderBegin, leftInorderEnd, postorder, leftPostorderBegin, leftPostorderEnd);
    39. root->right = traversal(inorder, rightInorderBegin, rightInorderEnd, postorder, rightPostorderBegin, rightPostorderEnd);
    40. return root;
    41. }
    42. public:
    43. TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
    44. if (inorder.size() == 0 || postorder.size() == 0) return NULL;
    45. // 左闭右开的原则
    46. return traversal(inorder, 0, inorder.size(), postorder, 0, postorder.size());
    47. }
    48. };

      117. 填充每个节点的下一个右侧节点指针 II

    链接 : 

    . - 力扣(LeetCode)

    层序遍历 , 借助一个pre结点 来 将每一层的结点的next指针指向右边的结点 ;

    1. class Solution {
    2. public:
    3. Node* connect(Node* root) {
    4. // 层序遍历
    5. queue<Node*> que ;
    6. if(root!=nullptr) que.push(root) ;
    7. while(!que.empty()){
    8. int size = que.size() ;
    9. Node* pre ;
    10. Node* cur ;
    11. for(int i=0;i<size;i++){
    12. if(i==0){
    13. pre = que.front() ;
    14. cur = pre ;
    15. que.pop() ;
    16. }else {
    17. cur = que.front() ;
    18. que.pop() ;
    19. pre -> next = cur ;
    20. pre = cur ;
    21. }
    22. if(cur->left) que.push(cur->left);
    23. if(cur->right) que.push(cur->right);
    24. }
    25. }
    26. return root ;
    27. }
    28. };

    114 . 二叉树展开成链表

    其实就是一个递归的过程 ;

    详细请看lc大佬的题解 :  

     - 力扣(LeetCode)b​​​​​​​t

    题中函数实现的三个步骤 : 

    将root的左子树展开成链表,将root的右子树展开成链表,将root的左子树链表插到右子树链表头节点前 ;(注意清空左指针)

    然后给出递归代码 : 

    1. class Solution {
    2. public:
    3. void flatten(TreeNode* root) {
    4. if(root == nullptr) return ;
    5. flatten(root->left) ;
    6. flatten(root->right) ;
    7. TreeNode* tmp = root->right ;
    8. root->right = root->left ;
    9. root->left = nullptr ;
    10. while(root->right != nullptr) root = root -> right ;
    11. root->right = tmp ;
    12. }
    13. };

    112 . 路径总和

    深度优先遍历,查找每一条路径是否能够和为targetSum;

    用递归实现 ;

    具体请看代码+注释 : 

    1. class Solution {
    2. public:
    3. bool dfs(TreeNode* root ,int t){
    4. // 1 . 递归终止条件编写 :
    5. // 左右子树全空,且t=0,表示找到一条路径和为t
    6. if(!root->left && !root->right && t==0) return true ;
    7. // 左右子树全空 , 但t!=0,直接返回false;
    8. if(!root->left && !root->right) return false;
    9. // 2 . 编写递归逻辑 :
    10. if(root->left){
    11. if(dfs(root->left , t - root->left->val))
    12. return true ;
    13. }
    14. if(root -> right){
    15. if(dfs(root->right , t - root->right->val))
    16. return true ;
    17. }
    18. return false ;
    19. }
    20. bool hasPathSum(TreeNode* root, int t) {
    21. if(!root) return false ;
    22. return dfs(root , t - root->val) ;
    23. }
    24. };

    129 . 求根节点到叶子结点的数字之和

    深度优先

    采取先序遍历的方式 ,找到每一个叶子节点 ,然后返回其和 ,先处理root的数据,然后遍历左子树和右子树 ;

    1. class Solution {
    2. public:
    3. int dfs(TreeNode* root,int k){
    4. if(root == nullptr) return 0 ;
    5. // 深度优先 , 中左右 --> 先序遍历
    6. int sum = k * 10 + root -> val ;
    7. if(!root->left && !root->right) return sum ;
    8. return dfs(root->left,sum) + dfs(root->right,sum) ;
    9. }
    10. int sumNumbers(TreeNode* root) {
    11. return dfs(root , 0) ;
    12. }
    13. };

    124 . 二叉树中的最大路径和

    采用动态规划的思想 :

        // 思考从下到上的顺序

        // 一个结点如果作为根节点 , 那么ress(贡献) = root->val + max(max_left,max_right)

        // 那么它对自己根节点的贡献也就是res ;

        // 结点作为路径的子节点,那么ans = max(ans,root->val+max_left+max_right)

        // 递归 , 在遍历每个节点的过程中 ,跟新最大值 即可

    1. class Solution {
    2. public:
    3. // 思考从下到上的顺序
    4. // 一个结点如果作为根节点 , 那么ress(贡献) = root->val + max(max_left,max_right)
    5. // 那么它对自己根节点的贡献也就是res ;
    6. // 结点作为路径的子节点,那么ans = max(ans,root->val+max_left+max_right)
    7. // 递归 , 在遍历每个节点的过程中 ,跟新最大值 即可
    8. int ans = INT_MIN ;
    9. int get(TreeNode* root){
    10. if(root == nullptr) return 0 ;
    11. // 递归计算左右结点的最大贡献值
    12. int leftGain = max(get(root->left),0);
    13. int rightGain = max(get(root->right),0);
    14. // 计算作为子节点的最大路径和
    15. int ansP = root->val + leftGain + rightGain ;
    16. // 更新答案
    17. ans = max(ans , ansP) ;
    18. // 返回作为根节点的最大贡献
    19. int res = root->val + max(leftGain , rightGain) ;
    20. return res ;
    21. }
    22. int maxPathSum(TreeNode* root) {
    23. // 调用递归函数
    24. int k = get(root) ;
    25. return ans ;
    26. }
    27. };

    173 . 二叉搜索树迭代器

    先中序遍历 , 按顺序将所有结点的值存起来;

    然后按照题目要求模拟 ;

    1. class BSTIterator {
    2. private:
    3. void inorder(TreeNode* root, vector<int>& res) {
    4. if (!root) {
    5. return;
    6. }
    7. inorder(root->left, res);
    8. res.push_back(root->val);
    9. inorder(root->right, res);
    10. }
    11. vector<int> inorderTraversal(TreeNode* root) {
    12. vector<int> res;
    13. inorder(root, res);
    14. return res;
    15. }
    16. vector<int> arr;
    17. int idx;
    18. public:
    19. BSTIterator(TreeNode* root): idx(0), arr(inorderTraversal(root)) {}
    20. int next() {
    21. return arr[idx++];
    22. }
    23. bool hasNext() {
    24. return (idx < arr.size());
    25. }
    26. };

    222 . 完全二叉树的结点个数

    层序遍历 : 

    遍历每一层 , 将每一层的节点数加入ans中 ;

    1. class Solution {
    2. public:
    3. int countNodes(TreeNode* root) {
    4. if(root == nullptr) return 0 ;
    5. queue<TreeNode*> que ;
    6. que.push(root) ;
    7. int ans = 0 ;
    8. while(!que.empty()){
    9. int size = que.size() ;
    10. ans += size ;
    11. for(int i=0;i<size;i++){
    12. TreeNode* node = que.front();
    13. que.pop();
    14. if(node->left) que.push(node->left) ;
    15. if(node->right) que.push(node->right) ;
    16. }
    17. }
    18. return ans ;
    19. }
    20. };

    递归

    一个结点 如果 作为根节点 , 那么总结点数 也就是 1 + 左子树结点数 + 右子树节点数 ;

    这样用递归就好 ;

    1. class Solution {
    2. public:
    3. int getSum(TreeNode* node){
    4. if(node == nullptr) return 0 ;
    5. int l = getSum(node->left) ;
    6. int r = getSum(node->right) ;
    7. return l + r + 1 ;
    8. }
    9. int countNodes(TreeNode* root) {
    10. int ans = getSum(root);
    11. return ans ;
    12. }
    13. };

    236 . 二叉树的最近公共祖先

    详细参考 : 代码随想录

    采用后序遍历的思想 , 回溯解决 ;

     根据题目定义 : 

    若 root是 p,q的 最近公共祖先 ,则只可能为以下情况之一:

    1 . p和 q在 root的子树中,且分列 root的 异侧(即分别在左、右子树中);
    2 . p=root ,且 q 在 root的左或右子树中;
    3 . q=root,且 p 在 root 的左或右子树中;

    1. class Solution {
    2. public:
    3. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    4. if(root == nullptr || root == p || root == q) return root;
    5. TreeNode *left = lowestCommonAncestor(root->left, p, q);
    6. TreeNode *right = lowestCommonAncestor(root->right, p, q);
    7. if(left == nullptr) return right;
    8. if(right == nullptr) return left;
    9. return root;
    10. }
    11. };

    参考 : 

  • 相关阅读:
    RocketMQ——MQ基础知识
    大模型时代的具身智能系列专题(六)
    python 进行图片的文字识别
    C语言中操作符的详细介绍
    Win11怎么安装语音包?Win11语音包安装教程
    加密流量研究方向
    【Linux】400行纯C语言代码带你【手撕线程池】
    【Unity程序技巧】Input管理器
    温敏壳聚糖水凝胶细胞因子复合支架/季铵盐壳聚糖水凝胶三维支架复合GNDF载间充质干细胞的制备
    好好回答下 TCP 和 UDP 的区别!
  • 原文地址:https://blog.csdn.net/ros275229/article/details/136210383