算法練習之二叉樹的最小深度,路徑總和

1.二叉樹的最小深度php

給定一個二叉樹,找出其最小深度。java

最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。node

說明: 葉子節點是指沒有子節點的節點。this

示例:
給定二叉樹 [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
返回它的最小深度  2.

javaspa

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        
        if(root==null) return 0;
        int left = minDepth(root.left);
        int right = minDepth(root.right);
        if(left!=0&&right!=0){
            return 1+Math.min(left,right);
        }
        return 1+left+right;
    }
}

phpcode

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($value) { $this->val = $value; }
 * }
 */
class Solution {

    /**
     * @param TreeNode $root
     * @return Integer
     */
    function minDepth($root) {
        if(empty($root)) return 0;
        $left = $this->minDepth($root->left);
        $right = $this->minDepth($root->right);
        if($left!=0&&$right!=0){
            return 1+min($left,$right);
        }
        return 1+$left+$right;
    }
}

2.路徑總和blog

給定一個二叉樹和一個目標和,判斷該樹中是否存在根節點到葉子節點的路徑,這條路徑上全部節點值相加等於目標和。it

說明: 葉子節點是指沒有子節點的節點。io

示例: 
給定以下二叉樹,以及目標和 sum = 225
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1
返回 true, 由於存在目標和爲 22 的根節點到葉子節點的路徑 5->4->11->2。

 javafunction

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root==null) return false;
        if(root.left==null&&root.right==null)
            return sum-root.val==0;
        return hasPathSum(root.left, sum-root.val)||hasPathSum(root.right, sum-root.val);
    }
}

php

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($value) { $this->val = $value; }
 * }
 */
class Solution {

    /**
     * @param TreeNode $root
     * @param Integer $sum
     * @return Boolean
     */
    function hasPathSum($root, $sum) {
        if(empty($root)) return false;
        if(empty($root->left)&&empty($root->right))
            return $sum-$root->val==0;
        return $this->hasPathSum($root->left, $sum-$root->val)||$this->hasPathSum($root->right, $sum-$root->val);
    }
}
相關文章
相關標籤/搜索