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. [置顶] ZK高级特性:Style定制与客户端集成

    1.ZK与传统MVC框架的集成 由于ZK应用本质上也是基于标准Web技术Servlet框架,因此与其它MVC框架的集成没有什么特别的, 以一个典型场景为例——为一个现有的Web项目(前端采用WebWo ...

  2. 【转】CentOS图形界面的开启与关闭

    源自:http://blog.sina.com.cn/s/blog_4a1f76860100zpus.html 安装CentOS 5.6系统的时候我没有先装任何组件,现在用X Window,需要再安装 ...

  3. Use eplipse to develop Python project

    Source: This is the example how to use eclipse and python. http://www.360doc.com/content/15/0206/10/ ...

  4. AndroidStudio 使用Hide API

    1.反射法 速度慢 2.生成新的android.jar 通常需要隐藏API的地方并不多 不需要整个都编译 而且编译出的framework.jar也不全 缺少java.*和javax.* 所以只把需要的 ...

  5. SQL Server ansi_null_default | ansi_null_dflt_on

    先说一下这两个变量是一个意思,只是它们的作用范围不同 alter database dbTest set ansi_null_default on;  -- 这个的作用域是整个SQL Server   ...

  6. php基础知识笔记

    基本语法 php文件的后缀名可以是 .php .php3 .phtml 输出命令 echo , print 语句以;结束 注释 // /* */ 变量都带$前缀, 如: $x, $names, $th ...

  7. 安装AppManager

    http://www.searchvirtual.com.cn/showcontent_66884.htm

  8. easyui-layout中的收缩层无法显示标题问题解决

    先看问题描述效果图片: 如上,我的查询条件是放在layout下面的一个可收缩层中,初始是收缩的,title显示不出来的话对使用者很不方便,代码如下: <div id="__MODULE ...

  9. 第一次当Uber司机,就拉到漂亮妹纸

    黑马哥的Uber司机端装上很久了,一次活儿也没拉,心里一直有一种当“张师傅”的冲动.黑马哥当Uber司机,肯定不是为了图挣钱,也不是因为Uber有“新约炮神器”的称号,能通过“拉活”来泡妹纸.黑马哥体 ...

  10. Good Luck in CET-4 Everybody!(博弈)

    Good Luck in CET-4 Everybody! Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K ...