zoukankan      html  css  js  c++  java
  • 【面试题25】二叉树中和为某一值的路径

    【题目描述】

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

    【解决方案】

    用栈来存储路径,递归调用来遍历各个路径,如果符合条件,则进行打印。

    考虑测试用例:

    1. 二叉树中有一条或多条符合条件的路径;

    2. 二叉树中没有符合条件的路径;

    3. 指向二叉树结点的指针为null;

    我的代码实现,仅供参考:

     1         public static void FindPath(BinaryTreeNode node, int targetSum, int currentSum, Stack<int> path)
     2         {
     3             if (node == null)
     4                 return;
     5 
     6             path.Push(node.Value);
     7             currentSum += node.Value;
     8 
     9             if (currentSum < targetSum)
    10             {
    11                 FindPath(node.Left, targetSum, currentSum, path);
    12                 FindPath(node.Right, targetSum, currentSum, path);
    13             }
    14 
    15             //到叶子结点正好和值为targeNum,则打印路径
    16             if (currentSum == targetSum && node.Left == null && node.Right == null)
    17             {
    18                 PrintPath(path);
    19             }
    20 
    21             path.Pop();
    22         }
    23 
    24         public static void PrintPath(Stack<int> path)
    25         {
    26             List<int> list = path.ToList<int>();
    27 
    28             for (int i = list.Count - 1; i >= 0; i--)
    29             {
    30                 Console.WriteLine(list[i]);
    31             }
    32         }
  • 相关阅读:
    IP地址分类整理
    PHP
    [转载]数组的全排列问题
    使用 Homebrew 安装 Git
    Homebrew简介及安装
    iOS开发~CocoaPods使用详细说明
    关于目前自己iOS项目使用的第三方开源库
    IOS 时间格式 时间转换 大总结
    Xcode磁盘空间大清理
    Swift百万线程攻破单例(Singleton)模式
  • 原文地址:https://www.cnblogs.com/HuoAA/p/4807348.html
Copyright © 2011-2022 走看看