Musings
Public · Protected · Private
Compare two binary trees
-
2008-07-15 11:56Just compare two binary trees -- return true or false
-
2008-07-15 11:58//Simple binary tree class btelement { public int value; public btelement left = null; public btelement right = null; public btelement(int v) { value = v; } } // simple filling btelement root1 = new btelement(1); root1.left = new btelement(2); root1.left.left = new btelement(4); root1.right = new btelement(3); root1.right.left = new btelement(5); btelement root2 = new btelement(1); root2.left = new btelement(2); root2.left.left = new btelement(3); root2.right = new btelement(3); root2.right.left = new btelement(5); //Simple comparison label1.Text = comparetrees(root1 , root2 ).ToString() ; // Recursive binary tree comparisons private bool comparetrees(btelement a, btelement b) { if (a == null) {//make sure both are null else return false if (b == null) return true; else return false; } else { if (b == null) return false; else { // Do the real work if (a.value == b.value) {// if values aer same check children if ((comparetrees(a.left, b.left)) && (comparetrees(a.right, b.right))) return true; else return false; } else return false; } } }
-
2008-07-15 15:29Very good code, however I am concerned with memory usage for large trees while making recursive calls. Can we do it non recursively or in more optimal way?
This blog is frozen. No new comments or edits allowed.