Java实现求二叉树的路径和

题:

  

解:

  这道题考的是如何找出一个二叉树里所有的序列。

  我的思路是先从根节点开始遍历,找出所有的子节点,因为每个子节点只有一个父节点,再根据每个子节点向上遍历找出所有的序列,再判断序列的总和。

  这样解效率不高,但暂时只能想到这样。如果您有其余的解法,期望告知。

代码:

  

 1 package com.lintcode;
 2
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.Enumeration;
 6 import java.util.List;
 7
 8 import javax.swing.tree.DefaultMutableTreeNode;
 9 import javax.swing.tree.TreeNode;
10
11 /**
12  * 二叉树的路径和
13  * 给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值 的路径。
14  * 一个有效的路径,指的是从根节点到叶节点的路径。
15  * @author Administrator
16  */
17 public class Test_002 {
18 //    得到所有最下面的子节点,再根据子节点向上遍历得到序列,每个子节点只能有一个父节点,
19 //    所以可以得到所有的序列,再判断序列的值是否等于需要的值。
20     /**
21      * @param args
22      */
23     public static void main(String[] args) {
24         DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(2);
25         node1.add(new DefaultMutableTreeNode(2));
26         DefaultMutableTreeNode node7 = new DefaultMutableTreeNode(3);
27         node7.add(new DefaultMutableTreeNode(6));
28         node1.add(node7);
29         DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(4);
30         DefaultMutableTreeNode top = new DefaultMutableTreeNode(1);
31         top.add(node1);
32         top.add(node2);
33         binaryTreePathSum(top,5);
34         for (List<Integer> list : result) {
35             System.out.println(list);
36         }
37     }
38     static List<List<Integer>> result = new ArrayList<List<Integer>>();
39     /**
40      * @param root the root of binary tree
41      * @param target an integer
42      * @return all valid paths
43      */
44     public static void binaryTreePathSum(TreeNode root, int target) {
45         if (root.getChildCount()!=0) {
46             Enumeration nodes = root.children();
47             while (nodes.hasMoreElements()) {
48                 binaryTreePathSum((TreeNode)nodes.nextElement(),5);
49             }
50         } else {
51             addList(root,new ArrayList<Integer>(), 5);
52         }
53     }
54
55     public static void addList(TreeNode root, List<Integer> temp, int target) {
56         List<Integer> list = temp;
57         list.add(Integer.parseInt(root.toString()));
58         if (root.getParent()!=null) {
59             addList(root.getParent(), list, 5);
60         } else {
61             Collections.sort(list);
62             int count = 0;
63             for (Integer integer : list) {
64                 count+=integer;
65             }
66             if (count==target) {
67                 result.add(list);
68             }
69         }
70     }
71 }

  这段代码在我的机子上运行是没问题的,但是在LintCode上面运行时总是提示找不到TreeNode的getChildCount方法,如果您知道原因的话,期望留言,谢谢。

时间: 2024-07-31 10:45:28

Java实现求二叉树的路径和的相关文章

求二叉树的路径和(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. Note: A leaf is a node with no children. Example: Given the below binary tree and sum = 22, 1234567 5

【算法】求二叉树各路径结点之和并找出最大值的路径

说在前面的话 最近没事将大学里的<数据结构>(严蔚敏,吴伟民著)一书重拾温习,受益颇多,才发现工作之中诸多经验问题都找到了理论支撑. 当时觉得没用的书,现在只能嘲笑当时得多low... 现在依然很low... --! 事件背景 因实际工作中,遇到一个关于权重的问题,需要将数据关系中最大权重的路径找到,然后就想到了<数据结构>中的DFS... 此事勾起了我码砖的激情,让我本已平静的心再次荡漾... 为了简单说明这个问题,我就拿个二叉树的模型来叙述一下我要达成的目标 CASE Exam

[Leetcode] Binary tree maximum path sum求二叉树最大路径和

Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. For example:Given the below binary tree, 1 / 2 3 Return6. 思路:题目中说明起始节点可以是任意节点,所以,最大的路径和不一样要经过root,可以是左子树中某一条,或者是右子树中某一条,当然也可能是经过树的根节点root的.递归式是应该是这三者中

[LeetCode] Binary Tree Maximum Path Sum 求二叉树的最大路径和

Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. For example:Given the below binary tree, 1 / 2 3 Return 6. 这道求二叉树的最大路径和是一道蛮有难度的题,难就难在起始位置和结束位置可以为任意位置,我当然是又不会了,于是上网看看大神们的解法,看了很多人的都没太看明白,最后发现了网友Yu's C

编程之美3.8 求二叉树中节点的最大距离

描述:如果把二叉树看成一个图,父子节点之间的连线看成双向的,定义“距离”为两个节点之间边的个数.求二叉树中相距最远的两个节点的距离. 思路:相距最远的两个节点一定是叶子节点,且这两个叶子节点的路径有两种情况: 1. 该路径经过root节点,则两个叶子节点分属root.left和root.right为根的子树,而且是两个子树中距离root.left和root.right最远的叶子节点: 2. 该路径不经过root节点,则这两个叶子节点的root.left或root.right上: 根据以上分析,参

11求二叉树中节点的最大距离

转载请注明出处:http://www.cnblogs.com/wuzetiandaren/p/4253605.html 声明:现大部分文章为寻找问题时在网上相互转载,此博是为自己做个记录记录,方便自己也方便有类似问题的朋友,本文的思想也许有所借鉴,但源码均为本人实现,如有侵权,请发邮件表明文章和原出处地址,我一定在文章中注明.谢谢. 题目:如果我们把二叉树看成一个图,一棵树显示是一颗有向无环图,定义"距离"为两节点之间边的个数(不考虑方向).写一个程序,求一棵二叉树中相距最远的两个节点

求二叉树深度

概念: 1.二叉树深度:树中结点的最大层次称为树的深度或高度. 2.二叉树层次:从根开始定义起,根为第一层,根的孩子为第二层,以此类推. 要点: 1.递归. 2.二叉树深度为左右子树深度较大值+1. 代码: /* 求二叉树深度 by Rowandjj 2014/7/13 ------------------------------- 题目描述: 输入一棵二叉树,求该树的深度.从根结点到叶结点依次经过的结点(含根.叶结点)形成树的一条路径,最长路径的长度为树的深度. 输入: 第一行输入有n,n表示

求二叉树中任意两个结点的距离

求二叉树中任意两个结点的距离 实现步骤: 计算跟到第一个结点的距离: 计算跟到第二个结点的距离: 计算lca: 计算跟到lca结点的距离: 结果为(1) + (2) - 2 * (4),因为重复计算了两次的从跟到lca结点的距离: 1 class Node(object): def __init__(self, value=0): self.value = value self.left = self.right = None def get_path_length(root, n, path)

LeetCode OJ:Binary Tree Maximum Path Sum(二叉树最大路径和)

Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root. For exampl