在二元树中找出和为某一值的所有路径

来源:互联网 发布:怎么取消差评淘宝 编辑:程序博客网 时间:2024/06/03 18:08

4.在二元树中找出和为某一值的所有路径 
  题目:输入一个整数和一棵二元树。 
  从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
  打印出和与输入整数相等的所有路径。 
  例如输入整数22 和如下二元树 
  10 
    / \

  5  12 
  / \ 

4   7 
       则打印出两条路径:10, 12 和10, 5, 7。
 

public class PrintPath {public static void main(String[] args) {BiTree biTree=new BiTree();biTree.insert(10);biTree.insert(5);biTree.insert(4);biTree.insert(12);biTree.insert(7);biTree.inorder(biTree.getRoot());System.out.println();biTree.printPaths(biTree.getRoot(), 19);}}class BiTree{private Node root;private final int MAX_SIZE=10;public void printPaths(Node root,int sum){int[] path=new int[MAX_SIZE];helper(root,sum,path,0);}private void helper(Node root,int sum,int[] path,int top){path[top++]=root.getValue();sum-=root.getValue();if(root.getLeftChild()==null&&root.getLeftChild()==null){if(sum==0)printPath(path, top);}else{if(root.getLeftChild()!=null)helper(root.getLeftChild(), sum, path, top);if(root.getRightChild()!=null)helper(root.getRightChild(), sum, path, top);}top--;sum+=root.getValue();}private void printPath(int[] path,int top){for(int i=0;i<top;i++)System.out.print(path[i]+" ");System.out.println();}/* * java是值传递,这种递归方法似乎不可行public void addNode(Node root,int value){if(root==null){Node node=new Node(value);root=node;}else{if(root.getValue()>value){addNode(root.getLeftChild(), value);}else {addNode(root.getRightChild(), value);}}}*/// 插入方法public void insert(int value) {Node newNode = new Node(value);// 如果说没有节点if (root == null) {root = newNode;} else {Node current = root;Node parent;while (true) {parent = current;if (value < current.getValue()) {current = current.getLeftChild();if (current == null) {parent.setLeftChild(newNode);return;}} else {current = current.getRightChild();if (current == null) {parent.setRightChild(newNode);return;}}}}}//中序遍历public void inorder(Node root){if(root!=null){inorder(root.getLeftChild());root.display();inorder(root.getRightChild());}}public Node getRoot() {return root;}}class Node{private int value;private Node leftChild;private Node rightChild;public Node(int value){this.value=value;}public int getValue() {return value;}public void setValue(int value) {this.value = value;}public Node getLeftChild() {return leftChild;}public void setLeftChild(Node leftChild) {this.leftChild = leftChild;}public Node getRightChild() {return rightChild;}public void setRightChild(Node rightChild) {this.rightChild = rightChild;}public void display(){System.out.print(value+" ");}}



实现完后发现还是C语言实现比较方便。


0 0
原创粉丝点击