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.

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.

思路:深度遍历(后续遍历)。每当访问到叶子节点时,计算栈内的元素,也就是从根节点到叶子节点的路径。

public boolean hasPathSum(TreeNode root, int sum) {
Stack<TreeNode> stack = new Stack<>();
int total = 0;
if (root == null)
return false;
TreeNode qNode=root;
while (root != null) {
while (root.left != null) {
stack.push(root);
total += root.val;
root = root.left;
}
while (root != null && (root.right == null || root.right == qNode)) {
if(root.right==null&&root.left==null){//访问到叶子节点
if(total+root.val==sum){
return true;
}
}
qNode = root;// 记录上一个已输出节点
if (stack.empty())
return false;
root = stack.pop();
total-=root.val;
}
stack.push(root);
total+=root.val;
root = root.right;
}
return false;
}

这个题目中,叶子结点不是非常清楚,考虑这种情况

        1

       / 

      2  

 结果为1,应该是正确的,存在path。

在此回顾一下二叉树的遍历(参考http://maizi2011.iteye.com/blog/938749

  /** 递归实现前序遍历 */
  protected static void preorder(BTNode p) {
    if (p != null) {
      visit(p);
      preorder(p.getLeft());
      preorder(p.getRight());
    }
  }
  /** 递归实现中序遍历 */
  protected static void inorder(BTNode p) {
    if (p != null) {
      inorder(p.getLeft());
      visit(p);
      inorder(p.getRight());
    }
  }
  /** 递归实现后序遍历 */
  protected static void postorder(BTNode p) {
    if (p != null) {
      postorder(p.getLeft());
      postorder(p.getRight());
      visit(p);
    }
  }
  /** 非递归实现前序遍历 */
  protected static void iterativePreorder(BTNode p) {
    Stack<BTNode> stack = new Stack<BTNode>();
    if (p != null) {
      stack.push(p);
      while (!stack.empty()) {
        p = stack.pop();
        visit(p);
        if (p.getRight() != null)
          stack.push(p.getRight());
        if (p.getLeft() != null)
          stack.push(p.getLeft());
      }
    }
  }
  /** 非递归实现后序遍历 */
  protected static void iterativePostorder(BTNode p) {
    BTNode q = p;
    Stack<BTNode> stack = new Stack<BTNode>();
    while (p != null) {
      // 左子树入栈
      for (; p.getLeft() != null; p = p.getLeft())
        stack.push(p);
      // 当前节点无右子或右子已经输出
      while (p != null && (p.getRight() == null || p.getRight() == q)) {
        visit(p);
        q = p;// 记录上一个已输出节点
        if (stack.empty())
          return;
        p = stack.pop();
      }
      // 处理右子
      stack.push(p);
      p = p.getRight();
    }
  }
  /** 非递归实现中序遍历 */
  protected static void iterativeInorder(BTNode p) {
    Stack<BTNode> stack = new Stack<BTNode>();
    while (p != null) {
      while (p != null) {
        if (p.getRight() != null)
          stack.push(p.getRight());// 当前节点右子入栈
        stack.push(p);// 当前节点入栈
        p = p.getLeft();
      }
      p = stack.pop();
      while (!stack.empty() && p.getRight() == null) {
        visit(p);
        p = stack.pop();
      }
      visit(p);
      if (!stack.empty())
        p = stack.pop();
      else
        p = null;
    }
  }

【LeetCode】Path Sum ---------LeetCode java 小结的更多相关文章

  1. LeetCode:Path Sum I II

    LeetCode:Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such ...

  2. 【LeetCode】Path Sum 2 --java 二叉数 深度遍历,保存路径

    在Path SUm 1中(http://www.cnblogs.com/hitkb/p/4242822.html) 我们采用栈的形式保存路径,每当找到符合的叶子节点,就将栈内元素输出.注意存在多条路径 ...

  3. Binary Tree Maximum Path Sum leetcode java

    题目: Given a binary tree, find the maximum path sum. The path may start and end at any node in the tr ...

  4. LeetCode Path Sum IV

    原题链接在这里:https://leetcode.com/problems/path-sum-iv/description/ 题目: If the depth of a tree is smaller ...

  5. [LeetCode] Path Sum III 二叉树的路径和之三

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  6. [LeetCode] Path Sum II 二叉树路径之和之二

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...

  7. [LeetCode] Path Sum 二叉树的路径和

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

  8. [LeetCode] Path Sum IV 二叉树的路径和之四

    If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digit ...

  9. LeetCode: Path Sum 解题报告

    Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addi ...

随机推荐

  1. html字符实体对照表

  2. Umbraco隐藏属性

    Umbraco默认的Url地址,是根据Node路径来默认显示的,因此使用中文的话比较尴尬. 网上有传的方法,是修改源码,来实现Url的重写. 但实际大可不必如此麻烦,只需要增加两个类型为Textstr ...

  3. 11136-Hoax or what

    Each Mal-Wart supermarket has prepared a promotion scheme run by the following rules: A client who w ...

  4. 取得phpcms网站下所有栏目的内容链接

    今天做了一个小功能,就是取得公司网站的所有文章的内容地址,公司网站是用phpcms 做的,感觉还蛮简单的,记录下: <?php $conf['DB_USER'] = 'user'; $conf[ ...

  5. 拥抱开源,怎样关注Linux Kernel 邮件列表?

    现在开源如此火爆.以至于张口闭口不提到都仿佛不是搞IT 的.那么怎样拥抱开源?本文适合刚開始学习的人,如有大神至此,goto exit ! 一.怎样增加开源 以Linux 为例,这么一个成功的开源项目 ...

  6. oracle execute immediate

    declare   aa         ,);   l_cnt      );   i_yr       ;   i_curCode  ) :='001';   i_vDate    date := ...

  7. SQL Server索引进阶:第三级,聚集索引

    原文地址: Stairway to SQL Server Indexes: Level 3, Clustered Indexes 本文是SQL Server索引进阶系列(Stairway to SQL ...

  8. 雪碧图(sprite)

    雪碧图 是一种将网页上常用且不经常变动的小图标集中在一张大图中,根据网页需求来显示图片的技术. 可以提高网页加载速度,增加用户体验. 其原理是通过html块状元素建立一个满足需求的视图窗口,然后在窗口 ...

  9. 2015 5.16 C# 继承和多态

    类的层次结构有两种基本的构造方式  自顶向下  自底向上 基类的保护成员是指允许派生类的方法代码访问,而不是指通过派生类的对象访问 如果基类中的字段通过公有且可读写的属性进行了封装,那么建议将字段定义 ...

  10. C#复习二(Twenty First Day)

    呵呵,又来到了今天的总结.这次主要复习了一下字符串的一些处理.今天就来总结一下. 理论: —String 字符串,字符串可以看成字符数组,不可变特性(通过for循环,修改string中的元素,失败!) ...