leetcode: Symmetric Tree
判断一棵树是否对称,如果对称,中序遍历的结果一定也是对称的。
public boolean isSymmetric(TreeNode root) { // Start typing your Java solution below // DO NOT write main() function if(root == null) return true; ArrayList<Integer> ret = new ArrayList<Integer>(); inorder(root, ret); for(int i=0, j=ret.size()-1; i<j; i++, j--){ if(ret.get(i) != ret.get(j)) return false; } return true; } public void inorder(TreeNode root, ArrayList<Integer> ret){ if(root == null) return; if(root.left!=null) inorder(root.left, ret); ret.add(root.val); if(root.right!=null) inorder(root.right, ret); }
看了一下别人的代码,也可以在递归的过程中直接去判断。
public boolean isSymmetric(TreeNode root) { // Start typing your Java solution below // DO NOT write main() function if(root== null) return true; return ifSymmetric(root.left, root.right); } public boolean ifSymmetric(TreeNode tree1, TreeNode tree2){ if(tree1==null && tree2==null) return true; else if(tree1 == null || tree2 == null) return false; if(tree1.val != tree2.val) return false; else return (ifSymmetric(tree1.left, tree2.right) && ifSymmetric(tree1.right, tree2.left)); }