Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Q3 {
- public static void main(String[] args) {
- BinNode<Integer> t1 = build_tree_ok();
- BinNode<Integer> t2 = build_tree_notOk();
- //boolean res = onePath(t2);
- boolean res = yarik(t1);
- System.out.println(res);
- }
- public static boolean yarik(BinNode<Integer>t) {
- if(t.getLeft()==null && t.getRight()==null) {
- return true;
- }else {
- if(!(t.getLeft()==null)&&t.getRight()==null) {
- if(t.getLeft().getValue()==t.getValue()) {
- return yarik(t.getLeft());
- }else {
- return false;
- }else {
- if(t.getRight().getValue()==t.getValue()) {
- return yarik(t.getRight());
- }else {
- return false;
- }
- }
- }
- }
- }
- public static boolean isLeaf(BinNode<Integer> t) {
- if(t == null)
- return false;
- if(t.getLeft() == null && t.getRight() == null)
- return true;
- return false;
- }
- //correct solution part1
- private static boolean onePath(BinNode<Integer> t1) {
- boolean r = onePath2(t1, t1.getValue());
- return r;
- }
- //correct solution part2
- private static boolean onePath2(BinNode<Integer> t, int x) {
- if(t==null)
- return false;
- int val = t.getValue();
- if(val!=x)
- return false;
- if(isLeaf(t))
- return val==x;
- return onePath2(t.getLeft(), val) || onePath2(t.getRight(), val);
- }
- public static BinNode<Integer> build_tree_ok() {
- BinNode<Integer> nd1 = new BinNode<Integer>(2);
- nd1.setLeft(new BinNode<Integer>(1));
- BinNode<Integer> nd2 = new BinNode<Integer>(1);
- nd2.setLeft(new BinNode<Integer>(1));
- nd2.setRight(new BinNode<Integer>(2));
- nd2.getLeft().setRight(nd1);
- BinNode<Integer> nd3 = new BinNode<Integer>(1);
- nd3.setLeft(new BinNode<Integer>(1));
- nd3.setRight(new BinNode<Integer>(2));
- BinNode<Integer> nd4 = new BinNode<Integer>(1);
- nd4.setRight(new BinNode<Integer>(2));
- nd4.getRight().setRight(new BinNode<Integer>(1));
- nd4.setLeft(nd3);
- BinNode<Integer> root = new BinNode<Integer>(1);
- root.setRight(nd2);
- root.setLeft(nd4);
- return root;
- }
- public static BinNode<Integer> build_tree_notOk() {
- BinNode<Integer> nd1 = new BinNode<Integer>(1); nd1.setLeft(new
- BinNode<Integer>(1));
- BinNode<Integer> nd2 = new BinNode<Integer>(1); nd2.setLeft(new
- BinNode<Integer>(1)); nd2.setRight(new BinNode<Integer>(2));
- nd2.getLeft().setRight(nd1);
- BinNode<Integer> nd3 = new BinNode<Integer>(1); nd3.setLeft(new
- BinNode<Integer>(1)); nd3.setRight(new BinNode<Integer>(2));
- BinNode<Integer> nd4 = new BinNode<Integer>(1); nd4.setRight(new
- BinNode<Integer>(2)); nd4.getRight().setRight(new BinNode<Integer>(1));
- nd4.setLeft(nd3);
- BinNode<Integer> root = new BinNode<Integer>(2);
- root.setRight(nd2);
- root.setLeft(nd4);
- return root;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement