找到某條路徑上和爲必定數值的路徑.

import java.util.Stack;


public class Node {
    Node left;
    Node right;
    int value;
    
    public static void main(String args[]){
    	Node node7 = new Node(null, null, 7);
    	Node node12 = new Node(null, node7, 12);
    	Node node4 = new Node(null, null, 4);
    	Node node5 = new Node(node4, node7, 5);
    	Node node10 = new Node(node12, node5,10);
    	Stack stack = new Stack();
    	findPath(node10, 22, stack);
    }
    
    public Node(Node left, Node right, int value){
    	this.left = left;
    	this.right = right;
    	this.value = value;
    }
    public static void findPath(Node node, int sum, Stack stack){
    	stack.push(node.value);
    	sum -= node.value;
    	if(sum == 0){
    		printPath(stack);
    	} 
    	if (node.left != null){
    		findPath(node.left, sum, stack);
    	}
    	if(node.right != null){
    		findPath(node.right, sum, stack);
    	}
    	sum += node.value;
    	stack.pop();
    	return;
    }
    
    public static void printPath(Stack stack){
    	Object objs[] = stack.toArray();
    	System.out.println();
    	for(Object obj : objs){
    		System.out.print(obj+"->");
    	}
    }
}
相關文章
相關標籤/搜索