zoukankan      html  css  js  c++  java
  • 剑指offer(24)二叉树中和为某一值的路径

    题目描述

    输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径

    题目分析

    这题基本上一看就知道应该深度遍历整个树,并且把已经走过的节点的和与期望值作比较就行,如果走到底还不符合要求的话,就要回退值。

    代码

    function FindPath(root, expectNumber) {
      // write code here
      const list = [],
        listAll = [];
      return findpath(root, expectNumber, list, listAll);
    }
    function findpath(root, expectNumber, list, listAll) {
      if (root === null) {
        return listAll;
      }
      list.push(root.val);
      const x = expectNumber - root.val;
      if (root.left === null && root.right === null && x === 0) {
        listAll.push(Array.of(...list));
      }
      findpath(root.left, x, list, listAll);
      findpath(root.right, x, list, listAll);
      list.pop();
      return listAll;
    }

      

  • 相关阅读:
    类别的三个作用
    require()
    commonJS
    ng-app&data-ng-app
    《css网站布局实录》(李超)——读书札记
    高性能JS(读书札记)
    两个同级div重叠的情况
    前端性能优化
    正则表达式
    ajax
  • 原文地址:https://www.cnblogs.com/wuguanglin/p/findPath.html
Copyright © 2011-2022 走看看