Determine if given tree is a subtree using dfs - java

I'm trying to determine if one tree (t) is a subtree of another tree (s).
This is a link to the leetcode which explains the problem thoroughly:https://leetcode.com/problems/subtree-of-another-tree/
My approach: I have one function that does a dfs on s and compares each node to the root of t in another function to determine if t is a subtree of s
My solution doesn't work for when s=[1,1] and t=[1], although I think it should be working. Could you please look at my code and explain what's wrong.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSubtree(TreeNode s, TreeNode t) {
/* dfs on s, at each node running a compare tree function for s at that node and
root of t*/
if(s == null || t == null) {
return false;
}
return dfs(s, t);
}
public static boolean dfs(TreeNode s, TreeNode t) {
if(s == null) {
return false;
}
if(s.val == t.val) {
return isSameTree(s, t);
}
return dfs(s.left, t) || dfs(s.right, t);
}
public static boolean isSameTree(TreeNode s, TreeNode t) {
if(s == null || t == null) {
return s == t;
}
if(s.val != t.val) {
return false;
}
return isSameTree(s.left, t.left) && isSameTree(s.right, t.right);
}
}

You need to check for all nodes of s if t is a subtree of that node or not. If you stop at first node while performing dfs on s and its value is same as root of t but subtrees are different, there might be some another node of tree s whose value and subtree both are same as t.
In other words, you need to repeat your 1st step (perform dfs on s and compare each node of s to the root of t) until you have checked all nodes of s (dfs is complete on s) or found that t is subtree of s.
s t
(1) (1)
/
(1)
Do not return from root of s just because of same values of root of s and t. If t is not subtree of that node, keep doing dfs to find another node whose value and subtree both are same as t (left child of root of s in this case).
For more clarity, below is your code with corrected part highlighted:
class Solution {
public boolean isSubtree(TreeNode s, TreeNode t) {
/* dfs on s, at each node running a compare tree function for s at that node and
root of t*/
if(s == null || t == null) {
return false;
}
return dfs(s, t);
}
public static boolean dfs(TreeNode s, TreeNode t) {
if(s == null) {
return false;
}
// ==== Corrected below if ====
// apart from s.val == t.val, if isSameTree(s, t) is true at this
// point, return true; otherwise keep doing dfs for rest of the tree s
// other same value node of s can be the answer
if(s.val == t.val && isSameTree(s, t)) {
return true;
}
return dfs(s.left, t) || dfs(s.right, t);
}
public static boolean isSameTree(TreeNode s, TreeNode t) {
if(s == null || t == null) {
return s == t;
}
if(s.val != t.val) {
return false;
}
return isSameTree(s.left, t.left) && isSameTree(s.right, t.right);
}
}

Looks pretty good! Almost there!
This'd pass:
public class Solution {
public static final boolean isSubtree(
final TreeNode s,
final TreeNode t
) {
if (s == null) {
return false;
}
if (checkNextLevel(s, t)) {
return true;
}
return isSubtree(s.left, t) ||
isSubtree(s.right, t);
}
private static final boolean checkNextLevel(
final TreeNode s,
final TreeNode t
) {
if (s == null && t == null) {
return true;
}
if (
(s == null || t == null) ||
(s.val != t.val)
) {
return false;
}
return checkNextLevel(s.left, t.left) &&
checkNextLevel(s.right, t.right);
}
}

Related

Understanding recursion function while checking if a binary tree is a subtree of another one

I am trying to understand if a tree t is a subtree of tree s. I have the following code and it does not work.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private boolean result = false;
public boolean isSubtree(TreeNode s, TreeNode t) {
return isTinS(s, t);
}
public boolean isTinS(TreeNode s, TreeNode t) {
if (t==null) return true;
if (s==null) return false;
if (s.val == t.val) {
return isSame(s,t);
}
return isTinS(s.left, t) || isTinS(s.right, t);
}
public boolean isSame(TreeNode s, TreeNode t) {
if (s==null && t==null) return true;
if (s==null || t==null) return false;
return s.val==t.val && isSame(s.left, t.left) && isSame(s.right, t.right);
}
}
If I change the if condition in isTinS function, it works. I am having a hard time figuring out the difference between the two codes.
public boolean isTinS(TreeNode s, TreeNode t) {
if (t==null) return true;
if (s==null) return false;
if (isSame(s,t)) {
return true;
}
return isTinS(s.left, t) || isTinS(s.right, t);
}
Could someone explain how are they different or point me to some good resources for understanding such concepts?
Suppose the value at the root of t appeared twice in s, but only one of those was at the root of a subtree matching t. If your first code hit the wrong one first, it would return false and never go on to look for the other, while the second would continue the search.

Java test two binary trees are the same

Update:
The best solution should be:
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null&&q==null) return true;
if(p==null||q==null) return false;
return isSameTree(p.left, q.left)&&isSameTree(p.right, q.right)&&(p.val==q.val);
}
Update:
Thank you all, I know those other solutions you told me, but my question is that why my solution doesn't work. Is it because that I ignore some return values? Thank you!
I have written a code for determining whether two binary trees are the same, I used recursive method to search through the tree, but this code sometimes didn't work, could you please help me to figure it out?
Thanks a lot!
Here's the code:
/*Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
*/
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p!=null){
if(q!=null&&p.val==q.val){
isSameTree(p.left, q.left);
isSameTree(p.right, q.right);
}
else return false;
}else{
if(q!=null) return false;
}
return true;
}
Input:
[10,5,15]
[10,5,null,null,15]
Output:
true
Expected:
false
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p!=null){
if(q!=null&&p.val==q.val){
if(!isSameTree(p.left, q.left)) return false;
if(!isSameTree(p.right, q.right)) return false;
return true;
}
else return false;
}else{
if(q!=null) return false;
}
return true;
}
I'm assuming you have a get method to retrieve data.One way you can solve is to let isSameTree methods to accept null values and then compare.
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == q) {
return true;
}
if (p == null || q == null) {
return false;
}
return p.get().isSameTree(q.get()) &&
isSameTree(p.left(), q.left()) &&
isSameTree(p.right(), q.right());
}
Another way is the following:
public boolean isSameTree(TreeNode p, TreeNode q)
{
if (p == null && q == null)
return true;
if (p != null && q != null)
return (p.get == q.get
&& isSameTree(p.left, q.left)
&& isSameTree(p.right, q.right));
return false;
}
You are just calling isSameTree for the child trees, but not checking their return values. Concise and correct version:
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == q) { //Will accept null == null
return true;
}
return p != null && q != null && p.val == q.val &&
isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
Also, #duffymo was incorrect stating you needed to use .equals() instead of ==. You are comparing the val's, which are primitives.
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null)
return true;
if (p != null && q != null)
return (p.val == q.val
&& isSameTree(p.left, q.left)
&& isSameTree(p.right, q.right));
return false;
}
}

Finding a node in a binary search tree in java?

I am trying to write a method that returns the depth of a target int in a binary search tree. Right now it works for some smaller trees, but not always. Does anyone see where I may be going wrong?
static int count=1;
public static int findDepth(TreeNode<Integer> root, int target)
// pre: 0 or more elements in the tree, integer to search for
// post: return depth of target if found, -1 otherwise
{
count++;
if (root!=null)
{
if (root.getValue()<target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
else
{findDepth(root.getLeft(), target);
count--;
findDepth(root.getRight(), target);
}
}
else if (root.getValue()>target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
else
{findDepth(root.getLeft(), target);
count--;
findDepth(root.getRight(), target);
}
}
else if (root.getValue()==target)
return 1;
else
return -1;
}
return count;
}
There's a few things wrong.
It will never get into this case:
if (root.getValue()<target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
Also it will never get into this case:
else if (root.getValue()>target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
The biggest issue is that you're keeping a global static count, and recursively going through both left and right paths.
First of all, for a BST, there is no need to go both left and right.
Second, it's better to pass the count through a parameter rather than keeping a global.
Rather than fix your code, I'll post this working example for you to use as a reference:
public class Main
{
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.add(20);
tree.add(10);
tree.add(30);
tree.add(15);
tree.add(25);
tree.add(5);
tree.add(35);
tree.add(1);
tree.add(6);
tree.add(14);
tree.add(16);
tree.add(24);
tree.add(26);
tree.add(34);
tree.add(36);
int level = tree.getLevel(6);
System.out.println(level);
}
}
public class TreeNode
{
int data;
TreeNode left;
TreeNode right;
public TreeNode(int d){
data = d;
left = null;
right = null;
}
}
public class BinaryTree
{
TreeNode root;
public BinaryTree(){
root = null;
}
public int getLevel(int val) {
if (root == null) return 0;
return getLevelHelper(root, val, 0);
}
public int getLevelHelper(TreeNode node, int val, int level){
int retVal = -1;
if (node.data == val){
return level;
}
if (val < node.data && node.left != null){
retVal = getLevelHelper(node.left, val, level + 1);
}
else if (val > node.data && node.right != null){
retVal = getLevelHelper(node.right, val, level + 1);
}
return retVal;
}
public boolean add(int newData){
if (root == null){
root = new TreeNode(newData);
return true;
}
else{
TreeNode curr = root;
while (true){
if (curr.data == newData){
return false;
}
else if (curr.data > newData){
if (curr.left == null){
curr.left = new TreeNode(newData);
return true;
}
else{
curr = curr.left;
}
}
else{
if (curr.right == null){
curr.right = new TreeNode(newData);
return true;
}
else{
curr = curr.right;
}
}
}
}
}
}

Finding if a number is equal to sum of 2 nodes in a binary search tree

Here is my code that for this. I am traversing the whole tree and then doing a find on each node. find() takes O(log n), and so the whole program takes O(n log n) time.
Is there a better way to implement this program? I am not just talking of better in terms of time complexity but in general as well. How best to implement this?
public boolean searchNum(BinTreeNode node, int num) {
//validate the input
if (node == null) {
return false;
}
// terminal case for recursion
int result = num - node.item;
//I have a separate find() which finds if the key is in the tree
if (find(result)) {
return true;
}
return seachNum(node.leftChild, num) || searchNum(node.rightChilde, num);
}
public boolean find(int key) {
BinTreeNode node = findHelper(key, root);
if (node == null) {
return false;
} else {
return true;
}
}
private BinTreeNode findHelper(int key, BinTreeNode node) {
if (node == null) {
return null;
}
if (key == node.item) {
return node;
} else if (key < node.item) {
return findHelper(key, node.leftChild);
} else {
return findHelper(key, node.rightChild);
}
}
Finding two nodes in binary search tree sum to some value can be done in the similar way of finding two elements in a sorted array that sums to the value.
In the case with an array sorted from small to large, you keep two pointers, one start from beginning, one start from the end. If the sum of the two elements pointed by the pointers is larger than the target, you move the right pointer to left by one, if the sum is smaller than target, you move the left pointer to right by one. Eventually the two pointer will either points to two elements that sum to the target value, or meet in the middle.
boolean searchNumArray(int[] arr, int num) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == num) {
return true;
} else if (sum > num) {
right--;
} else {
left++;
}
}
return false;
}
If you do an in-order traversal of the binary search tree, it becomes a sorted array. So you can apply the same idea on binary search tree.
The following code do iterative in-order traversal from both directions. Stack is being used for the traversal, so the time complexity is O(n) and space complexity is O(h), where h is the height of the binary tree.
class BinTreeIterator implements Iterator<BinTreeNode> {
Stack<BinTreeNode> stack;
boolean leftToRight;
public boolean hasNext() {
return !stack.empty();
}
public BinTreeNode next() {
return stack.peek();
}
public void remove() {
BinTreeNode node = stack.pop();
if (leftToRight) {
node = node.rightChild;
while (node.rightChild != null) {
stack.push(node);
node = node.rightChild;
}
} else {
node = node.leftChild;
while (node.leftChild != null) {
stack.push(node);
node = node.leftChild;
}
}
}
public BinTreeIterator(BinTreeNode node, boolean leftToRight) {
stack = new Stack<BinTreeNode>();
this.leftChildToRight = leftToRight;
if (leftToRight) {
while (node != null) {
stack.push(node);
node = node.leftChild;
}
} else {
while (node != null) {
stack.push(node);
node = node.rightChild;
}
}
}
}
public static boolean searchNumBinTree(BinTreeNode node, int num) {
if (node == null)
return false;
BinTreeIterator leftIter = new BinTreeIterator(node, true);
BinTreeIterator rightIter = new BinTreeIterator(node, false);
while (leftIter.hasNext() && rightIter.hasNext()) {
BinTreeNode left = leftIter.next();
BinTreeNode right = rightIter.next();
int sum = left.item + right.item;
if (sum == num) {
return true;
} else if (sum > num) {
rightIter.remove();
if (!rightIter.hasNext() || rightIter.next() == left) {
return false;
}
} else {
leftIter.remove();
if (!leftIter.hasNext() || leftIter.next() == right) {
return false;
}
}
}
return false;
}
Chen Pang has already given a perfect answer. However, I was trying the same problem today and I could come up with the following solution. Posting it here as it might help some one.
The idea is same as that of earlier solution, just that I am doing it with two stacks - one following the inorder(stack1) and another following reverse - inorder order(stack2). Once we reach the left-most and the right-most node in a BST, we can start comparing them together.
If the sum is less than the required value, pop out from stack1, else pop from stack2. Following is java implementation of the same:
public int sum2(TreeNode A, int B) {
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
TreeNode cur1 = A;
TreeNode cur2 = A;
while (!stack1.isEmpty() || !stack2.isEmpty() ||
cur1 != null || cur2 != null) {
if (cur1 != null || cur2 != null) {
if (cur1 != null) {
stack1.push(cur1);
cur1 = cur1.left;
}
if (cur2 != null) {
stack2.push(cur2);
cur2 = cur2.right;
}
} else {
int val1 = stack1.peek().val;
int val2 = stack2.peek().val;
// need to break out of here
if (stack1.peek() == stack2.peek()) break;
if (val1 + val2 == B) return 1;
if (val1 + val2 < B) {
cur1 = stack1.pop();
cur1 = cur1.right;
} else {
cur2 = stack2.pop();
cur2 = cur2.left;
}
}
}
return 0;
}
As far as I know, O(log n) is the best possible searching function you can use. I'm interested in the "n". If you're using a for-loop somewhere, consider using a hashtable in its stead. Hash table seeking is O(1) if I recall correctly.
From http://www.geeksforgeeks.org/find-a-pair-with-given-sum-in-bst/
/* In a balanced binary search tree isPairPresent two element which sums to
a given value time O(n) space O(logn) */
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// A BST node
struct node
{
int val;
struct node *left, *right;
};
// Stack type
struct Stack
{
int size;
int top;
struct node* *array;
};
// A utility function to create a stack of given size
struct Stack* createStack(int size)
{
struct Stack* stack =
(struct Stack*) malloc(sizeof(struct Stack));
stack->size = size;
stack->top = -1;
stack->array =
(struct node**) malloc(stack->size * sizeof(struct node*));
return stack;
}
// BASIC OPERATIONS OF STACK
int isFull(struct Stack* stack)
{ return stack->top - 1 == stack->size; }
int isEmpty(struct Stack* stack)
{ return stack->top == -1; }
void push(struct Stack* stack, struct node* node)
{
if (isFull(stack))
return;
stack->array[++stack->top] = node;
}
struct node* pop(struct Stack* stack)
{
if (isEmpty(stack))
return NULL;
return stack->array[stack->top--];
}
// Returns true if a pair with target sum exists in BST, otherwise false
bool isPairPresent(struct node *root, int target)
{
// Create two stacks. s1 is used for normal inorder traversal
// and s2 is used for reverse inorder traversal
struct Stack* s1 = createStack(MAX_SIZE);
struct Stack* s2 = createStack(MAX_SIZE);
// Note the sizes of stacks is MAX_SIZE, we can find the tree size and
// fix stack size as O(Logn) for balanced trees like AVL and Red Black
// tree. We have used MAX_SIZE to keep the code simple
// done1, val1 and curr1 are used for normal inorder traversal using s1
// done2, val2 and curr2 are used for reverse inorder traversal using s2
bool done1 = false, done2 = false;
int val1 = 0, val2 = 0;
struct node *curr1 = root, *curr2 = root;
// The loop will break when we either find a pair or one of the two
// traversals is complete
while (1)
{
// Find next node in normal Inorder traversal. See following post
// http://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/
while (done1 == false)
{
if (curr1 != NULL)
{
push(s1, curr1);
curr1 = curr1->left;
}
else
{
if (isEmpty(s1))
done1 = 1;
else
{
curr1 = pop(s1);
val1 = curr1->val;
curr1 = curr1->right;
done1 = 1;
}
}
}
// Find next node in REVERSE Inorder traversal. The only
// difference between above and below loop is, in below loop
// right subtree is traversed before left subtree
while (done2 == false)
{
if (curr2 != NULL)
{
push(s2, curr2);
curr2 = curr2->right;
}
else
{
if (isEmpty(s2))
done2 = 1;
else
{
curr2 = pop(s2);
val2 = curr2->val;
curr2 = curr2->left;
done2 = 1;
}
}
}
// If we find a pair, then print the pair and return. The first
// condition makes sure that two same values are not added
if ((val1 != val2) && (val1 + val2) == target)
{
printf("\n Pair Found: %d + %d = %d\n", val1, val2, target);
return true;
}
// If sum of current values is smaller, then move to next node in
// normal inorder traversal
else if ((val1 + val2) < target)
done1 = false;
// If sum of current values is greater, then move to next node in
// reverse inorder traversal
else if ((val1 + val2) > target)
done2 = false;
// If any of the inorder traversals is over, then there is no pair
// so return false
if (val1 >= val2)
return false;
}
}
// A utility function to create BST node
struct node * NewNode(int val)
{
struct node *tmp = (struct node *)malloc(sizeof(struct node));
tmp->val = val;
tmp->right = tmp->left =NULL;
return tmp;
}
// Driver program to test above functions
int main()
{
/*
15
/ \
10 20
/ \ / \
8 12 16 25 */
struct node *root = NewNode(15);
root->left = NewNode(10);
root->right = NewNode(20);
root->left->left = NewNode(8);
root->left->right = NewNode(12);
root->right->left = NewNode(16);
root->right->right = NewNode(25);
int target = 28;
if (isPairPresent(root, target) == false)
printf("\n No such values are found\n");
getchar();
return 0;
}
I found one bug under Chen Pang answer otherwise it's perfect. Bug is under remove method. All other code is same except remove method under iterator
suppose we have tree, per Chen Pang answer its will not consider element 18. similarly for left iterator
10
20
15 25
13 18
class BinTreeIterator implements Iterator<BinTreeNode> {
Stack<BinTreeNode> stack;
boolean leftToRight;
public boolean hasNext() {
return !stack.empty();
}
public BinTreeNode next() {
return stack.peek();
}
public void remove() {
BinTreeNode node = stack.pop();
if (leftToRight) {
node = node.rightChild;
while (node.rightChild != null) {
stack.push(node);
BinTreeNode leftNode=node.leftChild;
while (leftNode != null) {
stack.push(leftNode);
leftNode= node.leftChild;
}
node = node.rightChild;
}
} else {
node = node.leftChild;
while (node.leftChild != null) {
stack.push(node);
BinTreeNode rightNode=node.rightChild;
while (rightNode != null) {
stack.push(rightNode);
rightNode= node.rightChild;
}
node = node.leftChild;
}
}
}
public BinTreeIterator(BinTreeNode node, boolean leftToRight) {
stack = new Stack<BinTreeNode>();
this.leftToRight = leftToRight;
if (leftToRight) {
while (node != null) {
stack.push(node);
node = node.leftChild;
}
} else {
while (node != null) {
stack.push(node);
node = node.rightChild;
}
}
}
public static boolean searchNumBinTree(BinTreeNode node, int num) {
if (node == null)
return false;
BinTreeIterator leftIter = new BinTreeIterator(node,true);
BinTreeIterator rightIter = new BinTreeIterator(node,false);
while (leftIter.hasNext() && rightIter.hasNext()) {
BinTreeNode left = leftIter.next();
BinTreeNode right = rightIter.next();
int sum = left.item + right.item;
if (sum == num) {
return true;
} else if (sum > num) {
rightIter.remove();
if (!rightIter.hasNext() || rightIter.next() == left) {
return false;
}
} else {
leftIter.remove();
if (!leftIter.hasNext() || leftIter.next() == right) {
return false;
}
}
}
return false;
}
private static class BinTreeNode{
BinTreeNode leftChild;
BinTreeNode rightChild;
}
}
public boolean nodeSum(Node root, int num){
/*
Just subtract the sum from current value of the node and find
the node with remainder.
*/
if(root==null){
return false;
}
int val=num-root.key;
boolean found=find(root,val);
if(found){
return true;
}
boolean lSum=nodeSum(root.left,num);
boolean rSum=nodeSum(root.right,num);
return lSum||rSum;
}
public boolean find(Node root, int k){//same as search
if(root==null){
return false;
}
if(root.key==k){
return true;
}
if(root.key<k){
return find(root.right,k);
}else{
return find(root.left, k);
}
}

How do implement a breadth first traversal?

This is what I have. I thought pre-order was the same and mixed it up with depth first!
import java.util.LinkedList;
import java.util.Queue;
public class Exercise25_1 {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree(new Integer[] {10, 5, 15, 12, 4, 8 });
System.out.print("\nInorder: ");
tree.inorder();
System.out.print("\nPreorder: ");
tree.preorder();
System.out.print("\nPostorder: ");
tree.postorder();
//call the breadth method to test it
System.out.print("\nBreadthFirst:");
tree.breadth();
}
}
class BinaryTree {
private TreeNode root;
/** Create a default binary tree */
public BinaryTree() {
}
/** Create a binary tree from an array of objects */
public BinaryTree(Object[] objects) {
for (int i = 0; i < objects.length; i++) {
insert(objects[i]);
}
}
/** Search element o in this binary tree */
public boolean search(Object o) {
return search(o, root);
}
public boolean search(Object o, TreeNode root) {
if (root == null) {
return false;
}
if (root.element.equals(o)) {
return true;
}
else {
return search(o, root.left) || search(o, root.right);
}
}
/** Return the number of nodes in this binary tree */
public int size() {
return size(root);
}
public int size(TreeNode root) {
if (root == null) {
return 0;
}
else {
return 1 + size(root.left) + size(root.right);
}
}
/** Return the depth of this binary tree. Depth is the
* number of the nodes in the longest path of the tree */
public int depth() {
return depth(root);
}
public int depth(TreeNode root) {
if (root == null) {
return 0;
}
else {
return 1 + Math.max(depth(root.left), depth(root.right));
}
}
/** Insert element o into the binary tree
* Return true if the element is inserted successfully */
public boolean insert(Object o) {
if (root == null) {
root = new TreeNode(o); // Create a new root
}
else {
// Locate the parent node
TreeNode parent = null;
TreeNode current = root;
while (current != null) {
if (((Comparable)o).compareTo(current.element) < 0) {
parent = current;
current = current.left;
}
else if (((Comparable)o).compareTo(current.element) > 0) {
parent = current;
current = current.right;
}
else {
return false; // Duplicate node not inserted
}
}
// Create the new node and attach it to the parent node
if (((Comparable)o).compareTo(parent.element) < 0) {
parent.left = new TreeNode(o);
}
else {
parent.right = new TreeNode(o);
}
}
return true; // Element inserted
}
public void breadth() {
breadth(root);
}
// Implement this method to produce a breadth first
// search traversal
public void breadth(TreeNode root){
if (root == null)
return;
System.out.print(root.element + " ");
breadth(root.left);
breadth(root.right);
}
/** Inorder traversal */
public void inorder() {
inorder(root);
}
/** Inorder traversal from a subtree */
private void inorder(TreeNode root) {
if (root == null) {
return;
}
inorder(root.left);
System.out.print(root.element + " ");
inorder(root.right);
}
/** Postorder traversal */
public void postorder() {
postorder(root);
}
/** Postorder traversal from a subtree */
private void postorder(TreeNode root) {
if (root == null) {
return;
}
postorder(root.left);
postorder(root.right);
System.out.print(root.element + " ");
}
/** Preorder traversal */
public void preorder() {
preorder(root);
}
/** Preorder traversal from a subtree */
private void preorder(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.element + " ");
preorder(root.left);
preorder(root.right);
}
/** Inner class tree node */
private class TreeNode {
Object element;
TreeNode left;
TreeNode right;
public TreeNode(Object o) {
element = o;
}
}
}
Breadth first search
Queue<TreeNode> queue = new LinkedList<BinaryTree.TreeNode>() ;
public void breadth(TreeNode root) {
if (root == null)
return;
queue.clear();
queue.add(root);
while(!queue.isEmpty()){
TreeNode node = queue.remove();
System.out.print(node.element + " ");
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
}
Breadth first is a queue, depth first is a stack.
For breadth first, add all children to the queue, then pull the head and do a breadth first search on it, using the same queue.
For depth first, add all children to the stack, then pop and do a depth first on that node, using the same stack.
It doesn't seem like you're asking for an implementation, so I'll try to explain the process.
Use a Queue. Add the root node to the Queue. Have a loop run until the queue is empty. Inside the loop dequeue the first element and print it out. Then add all its children to the back of the queue (usually going from left to right).
When the queue is empty every element should have been printed out.
Also, there is a good explanation of breadth first search on wikipedia: http://en.wikipedia.org/wiki/Breadth-first_search
public void breadthFirstSearch(Node root, Consumer<String> c) {
List<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Node n = queue.remove(0);
c.accept(n.value);
if (n.left != null)
queue.add(n.left);
if (n.right != null)
queue.add(n.right);
}
}
And the Node:
public static class Node {
String value;
Node left;
Node right;
public Node(final String value, final Node left, final Node right) {
this.value = value;
this.left = left;
this.right = right;
}
}
//traverse
public void traverse()
{
if(node == null)
System.out.println("Empty tree");
else
{
Queue<Node> q= new LinkedList<Node>();
q.add(node);
while(q.peek() != null)
{
Node temp = q.remove();
System.out.println(temp.getData());
if(temp.left != null)
q.add(temp.left);
if(temp.right != null)
q.add(temp.right);
}
}
}
}
This code which you have written, is not producing correct BFS traversal:
(This is the code you claimed is BFS, but in fact this is DFS!)
// search traversal
public void breadth(TreeNode root){
if (root == null)
return;
System.out.print(root.element + " ");
breadth(root.left);
breadth(root.right);
}
For implementing the breadth first search, you should use a queue. You should push the children of a node to the queue (left then right) and then visit the node (print data). Then, yo should remove the node from the queue. You should continue this process till the queue becomes empty. You can see my implementation of the BFS here: https://github.com/m-vahidalizadeh/foundations/blob/master/src/algorithms/TreeTraverse.java
Use the following algorithm to traverse in breadth first search-
First add the root node into the queue with the put method.
Iterate while the queue is not empty.
Get the first node in the queue, and then print its value.
Add both left and right children into the queue (if the current
nodehas children).
Done. We will print the value of each node, level by level,by
poping/removing the element
Code is written below-
Queue<TreeNode> queue= new LinkedList<>();
private void breadthWiseTraversal(TreeNode root) {
if(root==null){
return;
}
TreeNode temp = root;
queue.clear();
((LinkedList<TreeNode>) queue).add(temp);
while(!queue.isEmpty()){
TreeNode ref= queue.remove();
System.out.print(ref.data+" ");
if(ref.left!=null) {
((LinkedList<TreeNode>) queue).add(ref.left);
}
if(ref.right!=null) {
((LinkedList<TreeNode>) queue).add(ref.right);
}
}
}
The following is a simple BFS implementation for BinaryTree with java 8 syntax.
void bfsTraverse(Node node, Queue<Node> tq) {
if (node == null) {
return;
}
System.out.print(" " + node.value);
Optional.ofNullable(node.left).ifPresent(tq::add);
Optional.ofNullable(node.right).ifPresent(tq::add);
bfsTraverse(tq.poll(), tq);
}
Then invoke this with root node and a Java Queue implementation
bfsTraverse(root, new LinkedList<>());
Even better if it is regular tree, could use following line instead as there is not only left and right nodes.
Optional.ofNullable(node.getChildern()).ifPresent(tq::addAll);
public static boolean BFS(ListNode n, int x){
if(n==null){
return false;
}
Queue<ListNode<Integer>> q = new Queue<ListNode<Integer>>();
ListNode<Integer> tmp = new ListNode<Integer>();
q.enqueue(n);
tmp = q.dequeue();
if(tmp.val == x){
return true;
}
while(tmp != null){
for(ListNode<Integer> child: n.getChildren()){
if(child.val == x){
return true;
}
q.enqueue(child);
}
tmp = q.dequeue();
}
return false;
}

Categories