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. ButterKnife使用小结

    项目官网:http://jakewharton.github.io/butterknife/ Github主页:https://github.com/JakeWharton/butterknife 这 ...

  2. PHP学习(前言)

    PHP学习(前言) 都说做IT技术的都该写写博客,以前没写过,现在开始写写吧.不是给别人看,就当是自己的学习笔记了. 大三结束了,该找工作了,对web前端感兴趣,想从事前端工作,自然要会一门后台语言了 ...

  3. 求模和求余(附加C语言实现)

    求模和求余的总体计算步骤如下: 1.求整数商  c = a/b 2.计算模或者余数 r = a - c*b 求模和求余的第一步不同,求余在取c的值时向0方向舍入;取模在计算c的值时向无穷小方向舍入. ...

  4. Angular form

    参考 http://blog.xebia.com/2013/10/15/angularjs-validating-radio-buttons/ http://stackoverflow.com/que ...

  5. asp.net core + angular2 的环境配置

    国内整个对 asp.net core  和 angular2这些新出来的关注度不是太好.跟国外比很大差距. 我在试着去做这个整合的时候也碰到不少问题. 最后通过查阅大量资料才弄明白. 我想肯定也会有类 ...

  6. 强化:把treeview的QString路径转换为QModelIndex节点,有了节点就什么都好办了

    http://doc.qt.io/qt-4.8/qdirmodel.html#index-2 甚至还能直接调用setData: setData(const QModelIndex &index ...

  7. 替换bmp图片中的颜色 good

    工作中,经常需要将bmp图片中的某个颜色修改为另外一种颜色.比如:将图片中的所有白色均修改成灰色. 平时都是拿画图板中的油漆桶工具一点一点的刷,费时又费力.(这么干好几年了 :( ) 今天抽空编了一个 ...

  8. Ubuntu下安装Wine&WineQQ+Phpstorm+wps+svn+vim(计划任的使用)+flashplayer+curl扩展

    一.安装Wine 1.添加PPA sudo add-apt-repository ppa:ubuntu-wine/ppa 2.更新列表 sudo apt-get update 3.安装Wine sud ...

  9. 关于webroot与web-inf

    struts.xml中配置redirect重定向路径的问题,要把转发的页面放到WebRoot下才能访问到,要是放在WEB-INF下面就访问不到.

  10. <td style="word-break:break-all"> 在html中控制自动换行

    在html中控制自动换行   其实只要在表格控制中添加一句 <td style="word-break:break-all">就搞定了. 其中可能对英文换行可能会分开一 ...