题目:

给定以下二叉树:

struct node

{

    node *left, *right;

    int value;

};

要求编写函数 node* foo(node *node, unsigned int m, unsigned int k);

输出以 node 为根的二叉树第 m 层的第 k 个节点值.(level, k 均从 0 开始计数)

注意:
此树不是完全二叉树;

所谓的第K个节点,是本层中从左到右的第K个节点

思路:

广度优先遍历,即层次遍历,通过队列来实现。

代码:

struct node{
    node *left, *right;

    int value;
};

node* foo(node *pRoot, unsigned int m, unsigned int k){
    if(pRoot==NULL)
        return NULL;

    queue<node*> tQueue;
    tQueue.push(pRoot);
    unsigned int total=1;

    while(m>1){
        if(total==0)
            return NULL;
        while(total>0){
            node* cur=tQueue.front();
            tQueue.pop();
            total--;
            if(cur->left!=NULL)
                tQueue.push(cur->left);
            if(cur->right!=NULL)
                tQueue.push(cur->right);
        }

        total=tQueue.size();
        m--;
    }

    if(total>=k){
        for(unsigned int i=0;i<k-1;i++)
            tQueue.pop();
        node* result=tQueue.front();
        return result;
    }
    else
        return NULL;
}

相关文章:

  • 2022-01-17
  • 2021-11-12
  • 2021-07-08
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-26
猜你喜欢
  • 2021-11-06
  • 2022-02-08
  • 2021-09-03
  • 2022-12-23
  • 2021-05-13
  • 2021-07-05
  • 2021-10-12
相关资源
相似解决方案