1. 程式人生 > >樹基礎訓練(一)

樹基礎訓練(一)

del node 搜索 表示 hid eas soft 葉子節點 目的

題目一: 

  求一個二叉樹的最小深度。

Given a binary tree, find its minimum depth. The minimum depth is the number of nodes aong the shortest path from the root node down to the neartest leaf node.

  TreeNode類:

技術分享圖片
public class TreeNode<T> {

    public T val;
    public TreeNode<T> left = null
; public TreeNode<T> right = null; public TreeNode<T> parent = null; public TreeNode(T val) { this.val = val; } }
View Code

  MinDepth類:

 1 public class MinDepth {
 2     public int run(TreeNode root) {
 3         if (root == null)
 4             return
0; 5 int depLeft = run(root.left); 6 int depRight = run(root.right); 7 if (depLeft == 0 || depRight == 0) 8 return 1 + depLeft + depRight; 9 return 1 + Math.min(depLeft, depRight); 10 } 11 }

題目二:

  路徑數字串之和。

Given a binary containing digits from 0-9 only, each root-to-leaf path path could represent a number.
An example is the root
-to-leaf path1->2->3which represents the number123 Find the total sum of all root-to-leaf numbers. For example, 1 2 3 The root-to-leaf path1->2represents the numbe 12. The root-to-leaf path1->3represents the number13. Return the sum = 12 + 13 = 25

  思路:題目的意思大概是,從根節點到葉子節點的路徑中,把其中的路徑上的數字拼接成一個字符串形成一個數字,需要把這些所有路徑上的字符串數字加起來。使用深搜的辦法即可輕松解決,遞歸搜索左子樹與右子樹,當搜索到葉子節點的時候表示路徑結束應該把當前形成的字符串加入到List中,等到所有的路徑搜索完畢,遍歷List將數字字符串轉化成數字然後加起來即可。註意結點類為題目一的結點類。

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class sum_root_leaf {

    public int sumNumbers(TreeNode<Integer> root) {
        if (root == null)
            return 0;
        f("", root);
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            sum += Integer.parseInt(list.get(i));
        }
        return sum;
    }

    List<String> list = new ArrayList<String>();

    /**
     * 帶前綴的dfs
     * 
     * @param pre
     * @param node
     */
    void f(String pre, TreeNode<Integer> node) {
        String _pre = pre + node.val;// 將當前節點的值,附加到pre上面
        if (node.left == null && node.right == null) {// 當前節點是葉子,結算
            list.add(_pre);
            return;
        }
        if (node.left != null)
            f(_pre, node.left);
        if (node.right != null)
            f(_pre, node.right);
    }

    @Test
    public void t() {
        sum_root_leaf obj = new sum_root_leaf();
        TreeNode<Integer> root = new TreeNode<>(1);
        TreeNode<Integer> l = new TreeNode<>(2);
        TreeNode<Integer> ll = new TreeNode<>(4);
        TreeNode<Integer> lr = new TreeNode<>(7);
        TreeNode<Integer> r = new TreeNode<>(3);
        TreeNode<Integer> rr = new TreeNode<>(5);
        TreeNode<Integer> rl = new TreeNode<>(8);
        root.left = l;
        root.right = r;
        l.left = ll;
        l.right = lr;
        r.right = rr;
        r.left = rl;
        int sum = obj.sumNumbers(root);
        System.out.println(sum);
    }

}

題目三:

  使用有序數組構建高度最低的BST。

Given a sorted(increasing order) array, write an algorithm to create a binary search tree with mininal height;

  思路:要想使得樹的高度最小那麽應該使樹的兩邊的節點盡可能分布均勻,那麽我們可以采用首尾相加相除的方式來得到當前的根節點(中間節點)是誰,取得中間節點之後之後那麽以中間為界限分為了左右兩個區間,對於左右兩個區間我們又可以使用同樣的方式來進行處理,那麽這個時候我們可以使用遞歸的方式來進行解決即可。註意結點類為題目一的結點類。

public class BSTWithMinHeight {
    TreeNode createMinBst(int[] arr) {
        return createMinBst(arr, 0, arr.length - 1);
    }

    private TreeNode createMinBst(int[] arr, int start, int end) {
        if (start > end)
            return null;

        int mid = start + ((end - start) >> 1);
        TreeNode left = createMinBst(arr, start, mid - 1);
        TreeNode right = createMinBst(arr, mid + 1, end);
        TreeNode res = new TreeNode(arr[mid]);
        res.left = left;
        res.right = right;
        return res;
    }

    public static void main(String[] args) {
        BSTWithMinHeight obj = new BSTWithMinHeight();
        int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
        TreeNode minBst = obj.createMinBst(arr);
        System.out.println(minBst);
    }
}

樹基礎訓練(一)