+ 2
Write Code to Determine if Two Trees are Identical
4 Respuestas
+ 5
Wait what is a tree?
+ 4
Tree
Graphically displays the directory structure of a path or of the disk in a drive.
+ 3
you mean like two tree structures or 2 "trees" like object tree?
0
Sorry, I don't know C or C++,I can write it in Java,here is my code:
The code is for binary tree, while if your tree is a k-nary tree, you can use recusive way to check every node between two trees.
class TreeNode{
public int key;
public TreeNode left;
public TreeNode right;
public TreeNode(int key){
this,key = key;
}
}
public class CheckIdentical{
public boolean isIdentical(TreeNode one, TreeNode two){
if(one == null && two == null){
return true;
} else if (one == null || two == null){
return false;
} else if (one.key != two.key){
return false;
}
return isIdentical(one.left, two.left) && isIdentical(one.right , two.right)
|| isIdentical(one.left, two.right) && isIdentical(one.right , two.left)
// the last line of code is used to check tweaked identical tree, if you assume a swap of the children of one node in the tree, the two trees are still same.