代码随想录算法训练营day15

6 阅读2分钟

111求二叉树的最小深度 1.要求掌握最小深度出现的具体条件,并不是单边节点不存在的情况,而是该节点不存在孩子时才达到最小深度 2.依旧按照三部法设计递归算法 下面时中序遍历的递归算法设计

class Solution {
public:
    int getminDepth(TreeNode* node){
        //设计终止条件
        if(node==nullptr) return 0;
        //设计单层递归
        int leftDepth=getminDepth(node->left);
        int rightDepth=getminDepth(node->right);
       

        //判断特殊情况
        if(node->right==nullptr&&node->left!=nullptr)
           return 1+leftDepth;
        if(node->right!=nullptr&&node->left==nullptr)
           return 1+rightDepth;
        int result=min(leftDepth,rightDepth)+1;
        return result;

    }
    int minDepth(TreeNode* root) {
        return getminDepth(root);
    }
};

先序遍历递归算法设计


class Solution {
public:
    int result;
    void getminDepth(TreeNode* node,int depth){
        //设计终止条件
        if(node==nullptr) return ;
        //设计单层递归
      // 中,处理逻辑:判断是不是叶子结点
        if (node -> left == nullptr && node->right == nullptr) {
            result = min(result, depth);
        }
        if (node->left) { // 左
            getminDepth(node->left, depth + 1);
        }
        if (node->right) { // 右
            getminDepth(node->right, depth + 1);
        }
        return ;

    }
    int minDepth(TreeNode* root) {
        if(root==nullptr) return 0;
        result=INT_MAX;
        getminDepth(root,1);
        return result;
    }
};

采用层次遍历迭代法求最小深度


class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root==nullptr) return 0;
        //层次遍历迭代法
        queue<TreeNode*> st;
        st.push(root);
        int depth=0;
        //执行入队迭代
        while(!st.empty()){
            int size=st.size();
            depth++;
            for(int i=0;i<size;i++){
               TreeNode* tmp=st.front();
               st.pop();
               //逐次入队
               if(tmp->left!=nullptr) st.push(tmp->left);
               if(tmp->right!=nullptr) st.push(tmp->right);
               //当达到终止条件时返回最小深度,最小深度的条件为两孩子均不存在
               if(tmp->left==nullptr&&tmp->right==nullptr) return depth;
            }
        }
        return depth;
    }
};

222.求完全二叉树的节点数量


class Solution {
public:
    int countNodes(TreeNode* root) {
        //提供递归终止条件
        if(root==nullptr) return 0;
        //执行递归和返回参数
        return 1+countNodes(root->left)+countNodes(root->right);
    }
};

110 求平衡二叉树 1.掌握平衡二叉树的细节逻辑 2.根据递归三要素进行算法设计

class Solution {
public:
    int  getHeight(TreeNode* node){
        //确定递归终止条件
        if(node==nullptr) return 0;
        //确定单层递归逻辑
        //设立左右子树高度
        int  leftHeight=getHeight(node->left);
        int  rightHeight=getHeight(node->right);
        if (leftHeight == -1) return -1;
        if (rightHeight==-1) return -1;
        return abs(leftHeight - rightHeight) > 1 ? -1 : 1 + max(leftHeight, rightHeight);
    }
    bool isBalanced(TreeNode* root) {
        return getHeight(root) == -1 ? false : true;
    }
};