Given a binary tree, get all nodes that don't have sibling node, excluding the root node.
Level order and pre order solutions.
1 import java.util.ArrayList; 2 import java.util.LinkedList; 3 import java.util.Queue; 4 5 public class NodeWithoutSibling { 6 public ArrayList<Integer> getNodesWithoutSiblingLevelOrder (TreeNode root){ 7 if(root == null) { 8 return null; 9 } 10 ArrayList<Integer> list = new ArrayList<Integer>(); 11 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 12 queue.add(root); 13 while(!queue.isEmpty()) { 14 TreeNode curr = queue.poll(); 15 if(curr.left != null) { 16 queue.add(curr.left); 17 } 18 if(curr.right != null) { 19 queue.add(curr.right); 20 } 21 if(curr.left != null && curr.right == null) { 22 list.add(curr.left.val); 23 } 24 if(curr.left == null && curr.right != null) { 25 list.add(curr.right.val); 26 } 27 } 28 return list; 29 } 30 31 public ArrayList<Integer> getNodesWithoutSiblingPreOrder1 (TreeNode root){ 32 ArrayList<Integer> list = new ArrayList<Integer>(); 33 preOrderHelper1(root, list); 34 return list; 35 } 36 private void preOrderHelper1(TreeNode node, ArrayList<Integer> list) { 37 if(node == null) { 38 return; 39 } 40 if(node.left != null && node.right == null) { 41 list.add(node.left.val); 42 } 43 if(node.left == null && node.right != null) { 44 list.add(node.right.val); 45 } 46 preOrderHelper1(node.left, list); 47 preOrderHelper1(node.right, list); 48 } 49 50 public ArrayList<Integer> getNodesWithoutSiblingPreOrder2 (TreeNode root) { 51 ArrayList<Integer> list = new ArrayList<Integer>(); 52 preOrderHelper2(root, list); 53 return list; 54 } 55 private void preOrderHelper2(TreeNode node, ArrayList<Integer> list) { 56 if(node == null) { 57 return; 58 } 59 if(node.left != null && node.right != null) { 60 preOrderHelper2(node.left, list); 61 preOrderHelper2(node.right, list); 62 } 63 else if(node.left != null) { 64 list.add(node.left.val); 65 preOrderHelper2(node.left, list); 66 } 67 else if(node.right != null) { 68 list.add(node.right.val); 69 preOrderHelper2(node.right, list); 70 } 71 } 72 73 public static void main(String[] args) { 74 TreeNode n1 = new TreeNode(1); 75 TreeNode n2 = new TreeNode(2); 76 TreeNode n3 = new TreeNode(3); 77 TreeNode n4 = new TreeNode(4); 78 TreeNode n5 = new TreeNode(5); 79 TreeNode n6 = new TreeNode(6); 80 n1.left = n2; n1.right = n3; 81 n2.right = n4; n3.left = n5; n5.left = n6; 82 NodeWithoutSibling test = new NodeWithoutSibling(); 83 ArrayList<Integer> list = test.getNodesWithoutSiblingPreOrder2(n1); 84 for(int i = 0; i < list.size(); i++) { 85 System.out.println(list.get(i)); 86 } 87 } 88 }