day 15层序遍历

102二叉树的层序遍历
二叉树的宽度深度都可以用层序遍历

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>>result;
        if(!root) return result;
        queue<TreeNode*>q;
        q.push(root);
        while(!q.empty()){
            int size = q.size();
            vector<int>path;
            while(size--){
                TreeNode* temp = q.front();
                path.push_back(temp->val);
                q.pop();
                if(temp->left) q.push(temp->left);
                if(temp->right) q.push(temp->right);
            }
            result.push_back(path);
        }
        return result;
    }
};

104. 二叉树的最大深度

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(!root) return 0;
        return max(maxDepth(root->left), maxDepth(root->right)) + 1;
    }
};

111. 二叉树的最小深度

最小深度

  1. 既没有左节点,又没有右节点 返回0
  2. 只有一个节点, 返回存在的子节点的深度
  3. 左右节点都有,返回小的那个
class Solution {
public:
    int minDepth(TreeNode* root) {
        if(!root) return 0;
        if(!root->left || !root->right) 
            return minDepth(root->left) + minDepth(root->right) + 1;
        return min(minDepth(root->right), minDepth(root->left)) + 1;
    }
};

226. 翻转二叉树

从当前root节点看问题
我的新左节点应该是把右子节点翻转后的返回节点
我的新右节点应该是把左子节点翻转后的返回节点

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(!root) return root;
        TreeNode * left = invertTree(root->right);
        TreeNode * right = invertTree(root->left);
        root->left = left;
        root->right = right;
        return root;
    }
};

直接使用swap进行值的更改

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(!root) return root;
        swap(root->left, root->right);
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};

101. 对称二叉树
本题比较的是左右子树,要另开一个函数

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        return judge(root->left, root->right);
    }
    bool judge(TreeNode* left, TreeNode* right){
        if(!left && !right) return true;
        if(!left || !right) return false;
        if(left->val != right->val) return false;
        return judge(left->left, right->right) && judge(left->right, right->left);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值