代码随想录 DAY 16 104 二叉树的深度111. 最小深度222. 完全二叉树的节点个数

104 二叉树的深度

递归

根节点+左右子树深度的最大值

class Solution {
public:
//递归
    int maxDepth(TreeNode* root) {
      if(root==nullptr){
          return 0;
      }   

      return 1+max(maxDepth(root->left),maxDepth(root->right));
    }
};

非递归

就是层序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
//非递归:层序遍历
    int maxDepth(TreeNode* root) {
     queue<TreeNode*> que;
     if(root!=nullptr){
       que.push(root);
     }

    int depth=0;

     while(!que.empty()){
       int size=que.size();
       depth++;
       for(int i=0;i<size;i++){
         TreeNode* node=que.front();
         que.pop();
         if(node->left) que.push(node->left);
         if(node->right) que.push(node->right); 
       }
     }
     
    return depth;
    }
};

111. 最小深度

和最大深度不一样,这个要考虑只有做、右子树的情况

class Solution {
public:
    int minDepth(TreeNode* root) {
        //为叶子节点的情况
        if(root==nullptr) return 0;
        //只有右节点
        if(root->left==nullptr&&root->right!=nullptr) return 1+minDepth(root->right);
        //只有左节点
        if(root->left!=nullptr&&root->right==nullptr) return 1+minDepth(root->left);

        return 1+min(minDepth(root->left),minDepth(root->right));
    }
};

非递归

同层序遍历,只不过是当找第一个到叶子节点时返回

class Solution {
public:
    int minDepth(TreeNode* root) {
       queue<TreeNode*> que;
     if(root!=nullptr){
       que.push(root);
     }

    int depth=0;

     while(!que.empty()){
       int size=que.size();
       depth++;
       for(int i=0;i<size;i++){
         TreeNode* node=que.front();
         que.pop();
         if(node->left) que.push(node->left);
         if(node->right) que.push(node->right); 
         //为什么最大深度加一条就对了?
         if(node->left==nullptr&&node->right==nullptr) return depth;
       }
     }
     
    return depth;
    }
};

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

就是遍历

class Solution {
public:
//就是遍历
    int countNodes(TreeNode* root) {
        stack<TreeNode*> st;
        int num=0;
        if(root!=nullptr){
            st.push(root);
            num++;
        }
        while(!st.empty()){
            TreeNode* node=st.top();
            st.pop();
            if(node->left){
                st.push(node->left);
                num++;
            }
            if(node->right){
                st.push(node->right);
                num++;
            }
        }
        return num;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值