编程之旅-Day19

目录

Day19-学习内容:

1.剑指Offer

面试题55:二叉树的深度

面试题55:判断是否平衡二叉树

面试题56:  数组中数字出现的次数

 2.Leetcode

例1:相同直线上的最大点数

例2:二叉树最大路径和

 3.2018年腾讯春招技术编程题

例4:小Q的歌单

4.2017年阿里巴巴秋招笔试题


1.剑指Offer

面试题55:二叉树的深度

题目描述:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

思路:递归

代码:

class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if(pRoot==nullptr){
            return 0;
        }
        int left=TreeDepth(pRoot->left);
        int right=TreeDepth(pRoot->right);
        return left>right?left+1:right+1;
    }
};

 

面试题55:判断是否平衡二叉树

题目描述:输入一棵二叉树,判断该二叉树是否是平衡二叉树。

思路:递归,为了每个节点只遍历一次,在每次遍历时需用指针记录下它的深度。

代码:

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(pRoot==nullptr){
            return true;
        }
        int depth=0;
        return IsBalanced(pRoot,&depth);
    }
    bool IsBalanced(TreeNode* pRoot,int *depth){
        if(pRoot==nullptr){
            *depth=0;
            return true;
        }
        int left,right;
        if(IsBalanced(pRoot->left,&left)&&IsBalanced(pRoot->right,&right)){
            int diff=left-right;
            if(diff<=1&&diff>=-1){
                *depth=1+(left>right?left:right);
                return true;
            }
        }
        return false;
    }
};

 

面试题56:数组中数字出现的次数

题目描述:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。

思路:使用二进制和异或操作,原理是一个数字异或它本身是等于零的。

代码:

class Solution {
public:
    void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) {
        if(data.empty()||data.size()<2) return;
        int len=data.size();
        
        int resultOR=0;
        for(int i=0;i<len;i++){
            resultOR^=data[i];
        }
        *num1=*num2=0;
        unsigned int indexof1=FindBitIs1(resultOR);
        for(int i=0;i<len;i++){
            if(IsBit1(data[i],indexof1)){
                *num1^=data[i];
            }
            else{
                *num2^=data[i];
            }
        }
    }
    unsigned int FindBitIs1(int num){
        int index=0;
        while(((num&1)==0)&&(index<8*sizeof(int))){
            num=num>>1;
            ++index;
        }
        return index;
    }
    
    bool IsBit1(int num, unsigned int index){
        num=num>>index;
        return (num&1);
    }
};

 

 2.Leetcode

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值