https://leetcode-cn.com/problems/symmetric-tree/description/
我的解决方案:比较笨拙,我直接按照左后根遍历一遍,然后再按照右后根遍历一遍,最后比较结果
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public static String lTreeToString(TreeNode tree, String string) {
if(tree==null) {
string+=null;
return string;
}
string = lTreeToString(tree.left, string);
string = lTreeToString(tree.right, string);
string += Integer.toString(tree.val);
return string;
}
public static String rTreeToString(TreeNode tree, String string) {
if(tree==null) {
string+=null;
return string;
}
string = rTreeToString(tree.right, string);
string = rTreeToString(tree.left, string);
string += Integer.toString(tree.val);
return string;
}
public static boolean isSymmetric(TreeNode root) {
//我的思路是分别对树进行左后根遍历和右后根遍历
//最后比较形成的结果是否相同
String lString=lTreeToString(root, "");
String rString=rTreeToString(root, "");
return lString.equals(rString)?true:false;
}
}
提交记录中耗时最短的代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
return isSym(root.left, root.right);
}
private boolean isSym(TreeNode left, TreeNode right) {
if(left == null|| right == null) {
return left==right?true:false;
}
if(left.val != right.val) return false;
return isSym(left.left, right.right) && isSym(left.right, right.left);
}
}
不得不说自己的思维还是不行啊。。。。