zoukankan      html  css  js  c++  java
  • 二叉树中和为某为某一值的路径

    public class 二叉树中和为某为某一值的路径
    {
        // 使用回溯算法 递归实现,分析好终止条件
        public void findPath(TreeNode root, int expectedNum)
        {
            if (root == null)
            {
                return;
            }
            if (expectedNum <= 0)
            {
                return;
            }
            int currentNum = 0;
            Stack<Integer> path = null;
            findPathCore(root, currentNum, path, expectedNum);
        }

        void findPathCore(TreeNode root, int currentNum, Stack<Integer> path,
                int expectedNum)
        {
            // 保存当前节点
            path.add(root.value);
            // 变化当前值
            currentNum += root.value;
            // flag 是否为叶子节点
            boolean isLeaf = root.left == null && root.right == null;
            // 找到相关路径
            if (currentNum == expectedNum && isLeaf)
            {
                // 输出相关路径 使用Iterator
                Iterator<Integer> res = path.iterator();
                while (res.hasNext())
                {
                    System.out.print(res.next());
                }
                System.out.println();

            }
            if (root.left != null)
            {
                findPathCore(root.left, currentNum, path, expectedNum);
            }
            if (root.right != null)
            {
                findPathCore(root.right, currentNum, path, expectedNum);
            }
            // 如果不满足天剑 最关键删除当前节点 进行回溯
            path.pop();
        }

    }

  • 相关阅读:
    Markdown基本语法
    面向对象
    LeetCode739 每日温度
    LeetCode155 最小栈
    LeetCode279 完全平方数
    LeetCode752 打开转盘锁
    LeetCode622 设计循环队列
    LeetCode200 岛屿的个数
    LeetCode61 旋转链表
    LeetCode138 复制带随机指针的链表
  • 原文地址:https://www.cnblogs.com/qingtianBKY/p/8258261.html
Copyright © 2011-2022 走看看