二叉树的创建和查找指定值路径
来源:互联网 发布:面板数据到底是怎样的 编辑:程序博客网 时间:2024/06/05 08:25
class Tree{ int value; Tree left; Tree right; public Tree(int value){ this.value=value; }}public class Find { private static Tree root; //用于构建二叉排序树 public void addTree(int value){ Tree newTree=new Tree(value); if(root==null){ root=newTree; }else{ Tree foucs=root; Tree parent; while(true){ parent=foucs; if(value<foucs.value){ foucs=foucs.left; if(foucs==null){ parent.left=newTree; return; } }else{ foucs=foucs.right; if(foucs==null){ parent.right=newTree; return; } } } } } //前序遍历打印二叉树 public void printTree(Tree root){ if(root==null){ return; } System.out.print(root.value+" "); printTree(root.left); printTree(root.right); } //查找二叉树路径节点值之和等于result的路径 public void findPath(Tree root,int result,ArrayList<Integer> list,int currentSum){ currentSum+=root.value; list.add(root.value); //判断当前结点是否是叶子节点 boolean isLeaf=root.left==null&&root.right==null; //判断是否和要求的值相等 if(currentSum==result&&isLeaf){ System.out.println("\n"); System.out.println("发现路径:"); for(Integer i:list){ System.out.print(i+"-"); } System.out.println("\n"); } if(root.left!=null){ findPath(root.left,result,list,currentSum); } if(root.right!=null){ findPath(root.right,result,list,currentSum); } if(list.size()>=0){ list.remove(list.size()-1); } } public static void main(String [] args){ int[] num={5,2,4,6,8,9,7}; Find f=new Find(); for(int i=0;i<num.length;i++){ f.addTree(num[i]); } f.printTree(root); ArrayList<Integer> list=new ArrayList<>(); f.findPath(root, 26, list, 0); }}
0 0
- 二叉树的创建和查找指定值路径
- 二叉树路径的查找(和为某一值)
- 二叉树指定路径和
- 二叉查找树的创建和遍历
- javascript实现二叉树的创建,遍历,添加,查找最大值最小值和指定值的寻找及删除功能——递归的多次运用
- 求二叉树中结点值的和为指定整数的所有路径
- 二叉查找树的 创建 查找 访问
- 在二叉树中找到累加和为指定值的最长路径长度
- 二叉树系列---找到累加和为指定值的最长路径长度
- 在二叉树中找到累加和为指定值的最长路径长度
- 在二叉树中找到累加和为指定值的最长路径长度
- 二叉树问题---在二叉树中找到累加和为指定值的最长路径长度
- NO4在二叉树中查找和为某值的所有路径
- 二叉树中查找和为某一值的所有路径
- 二叉查找树的简单创建和3种遍历
- 二叉搜索树(BST)的创建、插入、查找和删除
- 查找二叉树中和为某一个值的路径
- 二叉树的递归创建,以及二叉查找树查找的建立 和遍历查找的比较
- Spring-EL表达式
- 斯坦福大学机器学习笔记(4)-logistic回归
- 简单分析CVE-2015-1805
- 经典面试题:一张表区别DOM解析和SAX解析XML
- leetcode #44 in cpp
- 二叉树的创建和查找指定值路径
- linux 内核与用户空间通信
- Toast Notification
- 【LeetCode-189】Rotate Array(C++)
- HDU1331 Function Run Fun
- 1006. 换个格式输出整数 (15)
- 【c++程序】链表前插、插入和后插
- C++primer_第九章_顺序容器_学习跟踪
- Android USB Tethering