最短路径及最大树的应用

2 篇文章 0 订阅

Dijkstra算法:贪心算法的应用

这里写图片描述

这里写图片描述

1:  function Dijkstra(Graph, source):
2:      for each vertex v in Graph: // Initialization
3:          dist[v] := infinity // initial distance from source to vertex v is set to infinite
4:          previous[v] := undefined    // Previous node in optimal path from source
5:      dist[source] := 0   // Distance from source to source
6:      Q := the set of all nodes in Graph  // all nodes in the graph are unoptimized  
7:      while Q is not empty:   // main loop
8:          u := node in Q with smallest dist[ ]  //取最短的路径节点
9:          remove u from Q
10:         for each neighbor v of u:   // where v has not yet been removed from Q.
11:             alt := dist[u] + dist_between(u, v)  //离当前节点最近的节点最新的节点距离
12:             if alt < dist[v]    // Relax (u,v)//如果比之前的距离小,则重新赋予当前距离的值
13:                 dist[v] := alt
14:                 previous[v] := u
15:     return previous[ ]

求二叉树两节点和是否等于某个数

public class Solution {
    public boolean findTarget(TreeNode root, int k) {
        Set < Integer > set = new HashSet();
        return find(root, k, set);
    }
    public boolean find(TreeNode root, int k, Set < Integer > set) {
        if (root == null)
            return false;
        if (set.contains(k - root.val))
            return true;
        set.add(root.val);
        return find(root.left, k, set) || find(root.right, k, set);
    }
}

求最大树
1. The root is the maximum number in the array.
2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:

6
/ \
3 5
\ /
2 0
\
1

public class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return construct(nums, 0, nums.length);
    }
    public TreeNode construct(int[] nums, int l, int r) {
        if (l == r)
            return null;
        int max_i = max(nums, l, r);
        TreeNode root = new TreeNode(nums[max_i]);
        root.left = construct(nums, l, max_i);
        root.right = construct(nums, max_i + 1, r);
        return root;
    }
    public int max(int[] nums, int l, int r) {
        int max_i = l;
        for (int i = l; i < r; i++) {
            if (nums[max_i] < nums[i])
                max_i = i;
        }
        return max_i;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值