ARTS-12-計算二叉樹根到葉子節點之和

概述:
左耳朵耗子專欄《左耳聽風》 用戶自發每週完成一個ARTS:

1.Algorithm:每週至少做一個 leetcode 的算法題

2.Review:閱讀並點評至少一篇英文技術文章

3.Tip:學習至少一個技術技巧

4.Share:分享一篇有觀點和思考的技術文章

Algorithm
題目概述:

Given a binary tree containing digits from0-9only, each root-to-leaf 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 number12.
The root-to-leaf path1->3represents the number13.

Return the sum = 12 + 13 =25.

代碼:

/**
 * Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
 * <p>
 * An example is the root-to-leaf path1->2->3which represents the number123.
 * <p>
 * Find the total sum of all root-to-leaf numbers.
 * <p>
 * For example,
 * The root-to-leaf path1->2represents the number12.
 * The root-to-leaf path1->3represents the number13.
 * <p>
 * Return the sum = 12 + 13 =25.
 *
 * @author idea
 * @data 2019/7/14
 */


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

public class TotalDemo {

    private StringBuilder stb = new StringBuilder();
    public Integer sum=new Integer(0);

    public int sumNumbers(TreeNode root) {
        StringBuilder stb = new StringBuilder();
        findLeafNodeParent(root, stb);
        return sum;
    }

    /**
     * 查詢葉子節點
     *
     * @return
     */
    public void findLeafNodeParent(TreeNode root, StringBuilder current) {
        if (root == null) {
            return;
        }
        current.append(root.val);
        if (isLeaf(root)) {
            sum += Integer.parseInt(current + "");
        }
        findLeafNodeParent(root.left, current);
        findLeafNodeParent(root.right, current);
        current.deleteCharAt(current.length() - 1);
    }


    /**
     * 判斷是否是葉子節點
     *
     * @param root
     * @return
     */
    public boolean isLeaf(TreeNode root) {
        return root.left == null && root.right == null;
    }

    public static void main(String[] args) {
        TreeNode t1 = new TreeNode(1);
        TreeNode t2 = new TreeNode(2);
        TreeNode t3 = new TreeNode(3);
        TreeNode t4 = new TreeNode(4);
        TreeNode t5 = new TreeNode(5);
        TreeNode t6 = new TreeNode(6);

        t1.left = t2;
        t1.right = t3;
        t2.left = t4;
        t2.right = t5;
        t5.left = t6;

        TotalDemo td = new TotalDemo();
        Integer sum = td.sumNumbers(t1);
        System.out.println(sum);
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章