二叉树中和为某一值得所有路径

  

/**
 * 
 */
package jianzhioffer;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * @Description
 * @author liutao
 * @data 2016年4月22日
 */
public class a25_findPathInBTreeEqualsSum {
    public static void printPath(Stack<Node> s) {
        if (s == null||s.isEmpty())
            return;
        Stack<Node> copy = new Stack<Node>();
        while(!s.isEmpty()){
            copy.push(s.pop());
        }
        while(!copy.isEmpty()){
            System.out.print(copy.peek().data+" ");
            s.push(copy.pop());
        }
        System.out.println();
    }

    public static void printPathWithSum(Node root, int key) {
        if (root == null)
            return;

        Stack<Node> s = new Stack<Node>();
        Map<Node, Boolean> visited = new HashMap<Node, Boolean>();
        s.push(root);
        int sum = root.data;
        Node node = s.peek();
        visited.put(node, true);
        while (!s.isEmpty()) {
            if ((node.l == null && node.r == null)||visited.containsKey(node.l)&&visited.containsKey(node.r)) {
                if (sum == key) {
                    printPath(s);
                }
                sum -= s.peek().data;
                //System.out.println(s.peek().data);
                s.pop();
                if(s.isEmpty()) break;
                node = s.peek();
            }

            while (node.l != null) {
                if (!visited.containsKey(node.l)) {
                    visited.put(node.l, true);
                    sum += node.l.data;
                    s.push(node.l);
                    node=node.l;
                    //node = node.l;
                }else break;
            }

            if (node.r!= null) {
                if (!visited.containsKey(node.r)) {
                    visited.put(node.r, true);
                    sum += node.r.data;
                    s.push(node.r);
                    node = node.r;
                }
            }
        }
    }

    public static void main(String[] args) {
        Node tree1 = new Node(10);
        Node tree2 = new Node(5);
        Node tree3 = new Node(12);
        // Node tree4 = new Node(4);
        // Node tree5 = new Node(5);
        Node tree6 = new Node(4);
        Node tree7 = new Node(7);
        // Node tree8 = new Node(8);
        tree1.l = tree2;
        tree1.r = tree3;
        // tree2.l = tree4;
        // tree2.r = tree5;
        tree2.l = tree6;
        tree2.r = tree7;

        printPathWithSum(tree1, 22);
    }

}

class Node {
    int data;
    Node l, r;

    Node(int data) {
        this.data = data;
    }
}

 

posted on 2016-04-22 19:57  todayjust  阅读(139)  评论(0编辑  收藏  举报

导航