【LeetCode-面試演算法經典-Java實現】【112-Path Sum(路徑和)】

來源:互聯網
上載者:User

標籤:二叉樹   路徑   演算法   面試   java   

【112-Path Sum(路徑和)】 【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】 原題

  Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
  For example:
  Given the below binary tree and sum = 22,

              5             /             4   8           /   /           11  13  4         /  \              7    2      1

  return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

題目大意

  給定一棵二叉樹和一個和,判斷從樹的根結點到葉子結點的所有結點的和是否等於給定的和,如果等於,就返回true,否則返回false。

解題思路

  對樹進行遍曆,並且使用回溯法進行求解。

代碼實現

樹結點類

public class TreeNode {    int val;    TreeNode left;    TreeNode right;    TreeNode(int x) { val = x; }}

演算法實作類別

public class Solution {    private boolean stop = false; // 判斷是否已經找到答案    public boolean hasPathSum(TreeNode root, int sum) {        calculate(root, 0, sum);        return stop;    }    /**     * 計算根到葉子結點的和     * @param node 當前處理的節點     * @param cur 從根節點到當前結點之前的所有節點和     * @param sum 要求的和     */    private void calculate(TreeNode node, int cur, int sum) {        if (!stop && node != null) { // 還沒有找到答案,並且要處理的節點不為空白            // 如果是分葉節點,就檢查從根到當前分葉節點的和是否為sum,如果是就說明已經找到,改變stop            if (node.left == null && node.right == null && (node.val + cur == sum) ) {                stop = true;            }            // 如果是非分葉節點,繼續處理            if (node.left != null) {                calculate(node.left, cur + node.val, sum);            }            if (node.right != null) {                calculate(node.right, cur + node.val, sum);            }        }    }}
評測結果

  點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。

特別說明 歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47414069】

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

【LeetCode-面試演算法經典-Java實現】【112-Path Sum(路徑和)】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.