zoukankan      html  css  js  c++  java
  • <剑指offer> 第22题

    题目:

    输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。

    从根节点开始往下一直到叶节点所经过的节点形成一条路径。

    思路:

    在树的前序、中序、后序遍历中,只有前序遍历是首先访问根节点的。

    当用前序遍历的方式访问到某一节点时,把该节点添加到路径上,并累加该节点的值。

    如果该节点为叶节点并且路径中节点值的和刚好等于输入的整数,则当前的路径符合要求,我们把它打印出来。

    如果当前节点不是叶节点,则继续访问它的子节点。当前访问结束后,递归函数会自动回到它的的父节点。因此我们在函数退出之前要在路径上删除当前节点并减去当前节点的值,以确保返回父节点时路径刚好是从根节点到父节点的路径。

    深度优先搜索

    import java.util.ArrayList;
    import java.util.List;
    
    public class TwentySecond {
        public class BinarySearchTreeNode{
            int val;
            BinarySearchTreeNode left;
            BinarySearchTreeNode right;
        }
        public static void findPath(BinarySearchTreeNode root, int expectedSum){
            List<Integer> list = new ArrayList<>();
            if(root != null){
                findPath(root, 0, expectedSum, list);
            }
        }
    
        public static void findPath(BinarySearchTreeNode root, int curSum, int expectedSum, List<Integer> result){
            //如果节点不为空就进行处理
            if(root != null){
                //加上当前节点的值
                curSum += root.val;
                //将当前节点入队
                result.add(root.val);
                //如果当前节点的值小于期望的和
                if(curSum < expectedSum){
                    //递归处理左子树
                    findPath(root.left, curSum, expectedSum, result);
                    //递归处理右子树
                    findPath(root.right, curSum, expectedSum, result);
                }
                //如果当前和与期望的和相等
                else if(curSum == expectedSum){
                    //当前节点是叶节点,则输出结果
                    if(root.left == null && root.right == null){
                        System.out.println(result);
                    }
                }
                //移除当前节点
                result.remove(result.size() - 1);
            }
        }
    }
  • 相关阅读:
    for循环使用详解(c语言版)
    在Spring中轻松写日志
    项目可行性分析的困难
    控制台游戏引擎CGE——贪吃蛇
    python做数据分析pandas库介绍之DataFrame基本操作
    什么是 JWT -- JSON WEB TOKEN
    .net core 单体应用基于策略模式授权
    ABP VNext 初始化数据库时报错
    ABP VNext简介及使用代码生成器ABPHelper自动生成代码
    使用jenkins 在docker中发布.net core应用
  • 原文地址:https://www.cnblogs.com/HarSong13/p/11334283.html
Copyright © 2011-2022 走看看