网易笔试题:二叉树

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

思路:分两步
1.找到权值最大的位置和权值最小的位置;2.将它们到最近公共父节点的距离相加就能得到结果。

public static int getDis(TreeNode root) {
        int maxWeight = Integer.MIN_VALUE; //最大权值
        int minWeight = Integer.MAX_VALUE; //最小权值
        // 建立权重、结点编号的map
        HashMap<Integer, Integer> map1 = new HashMap<Integer, Integer>();
        LinkedList<TreeNode> queue1 = new LinkedList<TreeNode>();
        // 记录子、父节点的权重
        HashMap<Integer, Integer> map2 = new HashMap<Integer, Integer>();
        queue1.addFirst(root);
        int count = 0;
        map1.put(root.val, count++);
        while (!queue1.isEmpty()) {
            TreeNode temp = queue1.poll();
            if (temp.left != null) {
                queue1.addLast(temp.left);
                map1.put(temp.left.val, count++);
                map2.put(temp.left.val, temp.val);
            }
            if (temp.right != null) {
                queue1.addLast(temp.right);
                map1.put(temp.right.val, count++);
                map2.put(temp.right.val, temp.val);
            }
            if (temp.left == null && temp.right == null) { //叶子结点
                if (temp.val > maxWeight) {
                    maxWeight = temp.val;
                }
                if (temp.val < minWeight) {
                    minWeight = temp.val;
                }
            }
        }
        // 回溯的终止条件是回溯到同一个节点 此时 maxWeight = minWeight 
        int len1 = 0;
        int len2 = 0;
        while (maxWeight != minWeight) {
            if (map1.get(maxWeight) > map1.get(minWeight)) { 
                maxWeight = map2.get(maxWeight);
                len1++;
            } else if (map1.get(maxWeight) < map1.get(minWeight)) {
                minWeight = map2.get(minWeight);
                len2++;
            } else { //此时的父节点是公共父节点
                maxWeight = map2.get(maxWeight);
                minWeight = map2.get(minWeight);
                len1++;
                len2++;
            }
        }
        return len1 + len2;

    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值