zoukankan      html  css  js  c++  java
  • Path Sum

    Path Sum

    问题:

    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.

    思路:

      简单的DFS

    我的代码1:

    public class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            if(root == null)    return false;
            if(root.left == null && root.right == null)
            {
                if(root.val == sum) return true;
                else    return false;
            }
            return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
        }
    }
    View Code

    我的代码2:

    可以进行更加简洁的改进

    public class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            if(root == null)    return false;
            if(root.left == null && root.right == null)
            {
                return root.val == sum;
            }
            return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
        }
    }
    View Code

    学习之处:

      对于if else 简单的相等不相等,往往可以转换成一条语句,使程序更加简洁明了。

  • 相关阅读:
    带锚点URL同一页面滚动效果的实现
    思路先行
    transliteration -- 2个功能
    html5 section article
    fields('t')
    使用Bootstrap
    JavaScript Switch
    菜单
    写一个博客页面
    自动适应
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4328916.html
Copyright © 2011-2022 走看看