zoukankan      html  css  js  c++  java
  • (算法)二叉树的第m层第k个节点

    题目:

    给定以下二叉树:

    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;
    }
  • 相关阅读:
    day59_BOS项目_11
    day58_BOS项目_10
    shell 笔记
    docker + swarm 集群
    HDFS深入浅析
    FTP服务器常规操作
    linux shell 流程控制
    认识黑客常用的入侵方法
    Linux中常用的查看系统信息的命令
    解决Yum安装依赖问题
  • 原文地址:https://www.cnblogs.com/AndyJee/p/4712699.html
Copyright © 2011-2022 走看看