zoukankan      html  css  js  c++  java
  • 网易2016 实习研发工程师 [编程题]二叉树

    传送门

    有一棵二叉树,树上每个点标有权值,权值各不相同,请设计一个算法算出权值最大的叶节点到权值最小的叶节点的距离。二叉树每条边的距离为1,一个节点经过多少条边到达另一个节点为这两个节点之间的距离。

    给定二叉树的根节点root,请返回所求距离。

    题解:

    给每个节点编号(0 - total),用map记录每个节点的父节点

    找出最大权值叶子节点 和 最小权值 叶子节点的编号

    然后就是寻找最近公共祖先了

     1 /*
     2 struct TreeNode {
     3     int val;
     4     struct TreeNode *left;
     5     struct TreeNode *right;
     6     TreeNode(int x) :
     7             val(x), left(NULL), right(NULL) {
     8     }
     9 };*/
    10 
    11 class Tree {
    12 public:
    13     int getDis(TreeNode* root) {
    14         // write code here
    15         if(root == NULL) return 0;
    16         int ma = INT_MIN,mi = INT_MAX;
    17         int mapos = -1, mipos = -1;
    18         int total = 0;
    19         map<int,int> parent;
    20         parent[0] = -1;
    21         dfs(root,0,total,parent,ma,mi,mapos,mipos);
    22         int ans = 0;
    23         while(mapos != mipos) {
    24             if(mapos > mipos){
    25                 mapos = parent[mapos];
    26             }
    27             else{
    28                 mipos = parent[mipos];
    29             }
    30             ans ++;
    31         }
    32         return ans;
    33     }
    34     
    35     void dfs(TreeNode* root,int index,int &total,map<int,int> &parent,int &ma,int &mi,int &mapos,int &mipos) {
    36         if(root == NULL) {
    37             return;
    38         }
    39         if(root->left == NULL && root->right == NULL){
    40             if(root->val < mi) {
    41                 mi = root->val;
    42                 mipos = index;
    43             }
    44             if(root->val > ma) {
    45                 ma = root->val;
    46                 mapos = index;
    47             }
    48             return;
    49         }
    50         if(root->left != NULL) {
    51             total++;
    52             parent[total] = index;
    53             dfs(root->left,total,total,parent,ma,mi,mapos,mipos);
    54         }
    55         if(root->right != NULL) {
    56             total++;
    57             parent[total] = index;
    58             dfs(root->right,total,total,parent,ma,mi,mapos,mipos);
    59         }
    60     }
    61     
    62 };
  • 相关阅读:
    数据库新增“自动添加”类字段 auto_now_add 如何不影响之前数据
    django rest framework serializer中获取request中user方法
    django Table doesn't exist
    python 日期换算星期 蔡勒公式
    python pdfkit html转pdf响应式轮子 django例
    Python Excel 多sheet 多条数据 自定义写入
    Python 爬虫 Vimeo视频下载链接
    Python 快速排序 算法
    jvm内存模型
    JMV的学习
  • 原文地址:https://www.cnblogs.com/njczy2010/p/5726267.html
Copyright © 2011-2022 走看看