二叉树

二叉树

import java.util.ArrayList;
import java.util.List;

public class Test05 {
    public static void main(String[] args) {

        Node node4 = new Node(4, null, null);
        Node node5 = new Node(7, null, null);
        Node node2 = new Node(1, node4, node5);
        Node node3 = new Node(2, null, null);
        Node node1 = new Node(3, node2, node3);
        Test05 tsr = new Test05();
        System.out.println(tsr.check(node1, 8));

    }

    static class Node {
        //本节点的值
        int value;
        //左侧叶子节点,如果没有则为null
        Node left;
        //右侧叶子节点,如果没有则为null
        Node right;

        public Node(int value, Node left, Node right) {
            this.value = value;
            this.left = left;
            this.right = right;
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }

        public Node getLeft() {
            return left;
        }

        public void setLeft(Node left) {
            this.left = left;
        }

        public Node getRight() {
            return right;
        }

        public void setRight(Node right) {
            this.right = right;
        }
    }

    boolean check(Node root, int sum) {
        List<Integer> sumList = new ArrayList<>();
        int i = 0;
        sumReturn(root, i, sumList);
        System.out.println(sumList);
        if (sumList.contains(sum)) {
            return true;
        }else {
            return false;
        }
    }

    private void sumReturn(Node root, int i, List<Integer> sumList) {
        i = i + root.value;
        if (root.left == null && root.right == null) {
            sumList.add(i);
        } else {
            if (root.left != null) {
                sumReturn(root.left, i, sumList);
            }
            if (root.right != null) {
                sumReturn(root.right, i, sumList);
            }
        }
    }

}

  

posted @ 2018-07-02 22:57  江南孤狼  阅读(184)  评论(0编辑  收藏  举报