今天怎么状态这么不好,感觉这个题不简单啊,居然是easy。
看了答案才写出来。两种,recursive代码很简单,只是想清楚不容易,感觉怎么写helper要想明白。
iterative 写了好久,总是出错,用stack实现,每次push一对对应位置上的node,即应该相等的node。push进去之前就判断这对的值是否相等,pop出来之后,对于这一对,要检查一下前提条件(是否都具有左右子,对应左右子的值是否相等)然后就push相应的两对,分别是 left.left 和 right.right, 以及left.right和 right.left。
recursive:
public class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null )
return true;
return helper(root.left,root.right);
}
public boolean helper ( TreeNode left, TreeNode right){
if ( left == null || right == null ){
if ( left == right )
return true;
else return false;
}
return (left.val == right.val) && helper(left.left,right.right) && helper(left.right, right.left);
}
}
iterative:
public class Solution {
public boolean isSymmetric(TreeNode root) {
if ( root == null )
return true;
Stack <TreeNode> st = new Stack<TreeNode>();
if ( root.left != null ){
if ( root.right == null)
return false;
if ( root.left.val != root.right.val )
return false;
st.push(root.left);
st.push(root.right);
}
else{
if ( root.right != null)
return false;
}
while ( !st.empty()){
TreeNode rightc = st.pop();
TreeNode leftc = st.pop();
if ( rightc.left != null ){
if ( leftc.right == null)
return false;
if ( leftc.right.val != rightc.left.val )
return false;
st.push(leftc.right);
st.push(rightc.left);
}
else {
if ( leftc.right != null)
return false;
}
if ( leftc.left != null ){
if ( rightc.right == null)
return false;
if ( leftc.left.val != rightc.right.val )
return false;
st.push(leftc.left);
st.push(rightc.right);
}
else {
if ( rightc.right != null)
return false;
}
}
return true;
}
}