Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void printCommon(Node a, Node b) {
- Stack<Node> stackA = new Stack<>();
- Stack<Node> stackB = new Stack<>();
- Node currentA = a;
- Node currentB = b;
- while ((!stackA.isEmpty() || currentA != null) && (!stackB.isEmpty() || currentB != null)) {
- if (currentA != null) {
- stackA.push(currentA);
- currentA = currentA.left;
- } else if (currentB != null) {
- stackB.push(currentB);
- currentB = currentB.left;
- } else if (!stackA.isEmpty() && !stackB.isEmpty()) {
- currentA = stackA.pop();
- currentB = stackB.pop();
- if (currentA.data == currentB.data) {
- System.out.print(currentA.data + " ");
- currentA = currentA.right;
- currentB = currentB.right;
- } else if (currentA.data < currentB.data) {
- currentA = currentA.right;
- stackB.push(currentB);
- currentB = null;
- } else if (currentA.data > currentB.data) {
- currentB = currentB.right;
- stackA.push(currentA);
- currentA = null;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement