Created
July 30, 2018 15:09
-
-
Save jiankaiwang/22cb69165df2bae678347e760001f8d9 to your computer and use it in GitHub Desktop.
check whether the binary tree is the mirror tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Stack; | |
class NODE { | |
public String ch; | |
public NODE leftNode; | |
public NODE rightNode; | |
public NODE() { | |
ch = "_"; | |
leftNode = null; | |
rightNode = null; | |
} | |
public NODE(String getStr) { | |
ch = getStr; | |
} | |
} | |
public class main { | |
public static boolean checkMirror(NODE rootNode) { | |
Stack<NODE> st = new Stack<NODE>(); | |
String checkStr = ""; | |
NODE tmpNode = rootNode; | |
while(true) { | |
// find the node on the left-handed side | |
while(true) { | |
if(tmpNode.leftNode != null) { | |
st.push(tmpNode); | |
tmpNode = tmpNode.leftNode; | |
} else { | |
if(tmpNode.rightNode != null) { | |
st.push(tmpNode); | |
} else { | |
checkStr += tmpNode.ch; | |
} | |
break; | |
} | |
} | |
// no element on the stack | |
if(st.size() < 1) { | |
break; | |
} | |
while(true) { | |
tmpNode = st.pop(); | |
checkStr += tmpNode.ch; | |
// find the node on the right-handed side | |
if(tmpNode.rightNode != null) { | |
tmpNode = tmpNode.rightNode; | |
break; | |
} | |
} | |
} | |
System.out.println(checkStr); | |
// check palindrome | |
if(checkStr.length() == 1) { return true; } | |
else if(checkStr.length() == 2) { return false; } | |
for(int i = 0 ; i < checkStr.length() / 2 ; i++) { | |
//System.out.println(checkStr.charAt(i) + "," + checkStr.charAt(checkStr.length() - 1 - i)); | |
if(checkStr.charAt(i) != checkStr.charAt(checkStr.length() - 1 - i)) { | |
return false; | |
} | |
} | |
return true; | |
} | |
public static void main(String[] args) { | |
/* CBEDADEBC => CBED <-> DEBC | |
A | |
B | B | |
C D | D C | |
E | E | |
*/ | |
NODE root = new NODE("A"); | |
NODE l1a = new NODE("B"); | |
NODE l1b = new NODE("B"); | |
root.leftNode = l1a; | |
root.rightNode = l1b; | |
NODE l2a = new NODE("C"); | |
NODE l2b = new NODE("D"); | |
NODE l2c = new NODE("D"); | |
NODE l2d = new NODE("C"); | |
l1a.leftNode = l2a; | |
l1a.rightNode = l2b; | |
l1b.leftNode = l2c; | |
l1b.rightNode = l2d; | |
NODE l3a = new NODE("E"); | |
NODE l3b = new NODE("E"); | |
l2b.leftNode = l3a; | |
l2c.rightNode = l3b; | |
//System.out.println("Hello world, Java!"); | |
System.out.println(checkMirror(root)); | |
System.gc(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment