牛客网刷题笔记——树

求二叉树的层序遍历
给定一个二叉树,返回该二叉树层序遍历的结果
实现思路:BFS, 用队列保存每一层节点
1️⃣先将根节点入队
2️⃣当队列不为空
①求出当前队列len(即当前层)
②取出前len个节点,值存起来
③如果有孩子节点,压入队列
/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
   
public:
    /**
     * 
     * @param root TreeNode类 
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > levelOrder(TreeNode* root) {
   
        // write code here
        //实现思路,用队列保存节点,vector保存每一层遍历结果
        vector<vector<int>> res;
        if(root==nullptr)
            return res;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
   
            vector<int> tmp;
            int n=q.size();
            for(int i=0;i<n;i++){
   
                TreeNode* t=q.front();
                q.pop();
                tmp.push_back(t->val);
                if(t->left)
                    q.push(t->left);
                if(t->right)
                    q.push(t->right);
            }
            res.push_back(tmp);
        }
        return res;
        
    }
};

本题还有一个变式:之字形遍历,思路一致,只需要用一个bool标识奇数层还是偶数层,偶数层reverse一下即可

在二叉树中寻找最近的公共祖先

最近公共祖先和o1,o2有三种关系:

  • o1,o2分别在祖先左右两侧
  • 祖先是o1,o2在祖先左/右侧
  • 祖先是o2,o1在祖先左/右侧
    使用dfs深度遍历,如果节点为o1,o2中其中一个直接返回,如果节点超过叶子节点也返回
/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
   
public:
    /**
     * 
     * @param root TreeNode类 
     * @param o1 int整型 
     * @param o2 int整型 
     * @return int整型
     */
    int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
   
        // write code here
        return CommonAncestor(root,o1,o2)->val;
    }
    TreeNode* CommonAncestor(TreeNode* root,int o1,int o2){
   
        if(root==nullptr||root->val==o1||root->val==o2)
            return root;
        TreeNode* left=CommonAncestor(root->left, o1, o2);
        TreeNode* right=CommonAncestor(root->right, o1, o2);
        if (left == nullptr) {
     // 都在右侧
            return right;
        }
        if (right == nullptr) {
    // 都在左侧
            return left;
        }
        return root; // 在左右两侧
    }
};
二叉树的先序、中序、后序遍历
/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 * };
 */
vector<int> pre;
vector<int> in;
vector<int> post;
class Solution {
   
public:
    /**
     * 
     * @param root TreeNode类 the root of binary tree
     * @return int整型vector<vector<>>
     */
    void preorder(TreeNode* root){
   
        if(root 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值