iOS面试题合集

iOS面试题-数据结构篇(必问系列)

2020-11-18  本文已影响0人  iOS打工犭袁

数据结构

1.数据结构的存储一般常用的有几种?各有什么特点?

数据结构的存储一般常用的有两种 顺序存储结构 和 链式存储结构

2.集合结构 线性结构 树形结构 图形结构

3.单向链表 双向链表 循环链表

4.数组和链表区别

5.堆、栈和队列

队列

6.输入一棵二叉树的根结点,求该树的深度?

二叉树的结点定义如下:

struct BinaryTreeNode
{
    int m_nValue ;
    BinaryTreeNode* m_pLeft;
    BinarvTreeNode* m_pRight ;
}

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);
}

7.输入一课二叉树的根结点,判断该树是不是平衡二叉树?

方法1:

struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
};

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

bool IsBalanced(TreeNode* pRoot){
    if(pRoot==NULL)
        return true;
    int left=TreeDepth(pRoot->left);
    int right=TreeDepth(pRoot->right);
    int diff=left-right;
    if(diff>1 || diff<-1)
        return false;
    return IsBalanced(pRoot->left) && IsBalanced(pRoot->right);
}

方法2:

bool IsBalanced_1(TreeNode* pRoot,int& depth){
    if(pRoot==NULL){
        depth=0;
        return true;
    }
    int left,right;
    int diff;
    if(IsBalanced_1(pRoot->left,left) && IsBalanced_1(pRoot->right,right)){
        diff=left-right;
        if(diff<=1 || diff>=-1){
            depth=left>right?left+1:right+1;
            return true;
        }
    }
    return false;
}

bool IsBalancedTree(TreeNode* pRoot){
    int depth=0;
    return IsBalanced_1(pRoot,depth);
} 

推荐文集

注明:内容摘自网络,如有侵权联系小编删除

上一篇 下一篇

猜你喜欢

热点阅读