递归解法
class Solution { public boolean isSymmetric(TreeNode root) { if(root==null)return true; return dfs(root.left,root.right); } public boolean dfs(TreeNode l, TreeNode r) { if(l==null||r==null) return l==null&&r==null; if(l.val!=r.val)return false; return dfs(l.left,r.right)&&dfs(l.right,r.left); } }
递推解法
class Solution { public boolean isSymmetric(TreeNode root) { if(root==null)return true; Stack stack1 = new Stack (); Stack stack2 = new Stack (); TreeNode temp1 = root.left; TreeNode temp2 = root.right; while(temp1!=null||temp2!=null||!stack1.isEmpty()||!stack2.isEmpty()) { while(temp1!=null&&temp2!=null) { stack1.push(temp1); temp1 = temp1.left; stack2.push(temp2); temp2 = temp2.right; } if(temp1!=null||temp2!=null)return false; temp1 = stack1.pop(); temp2 = stack2.pop(); if(temp1.val!=temp2.val) return false; temp1 = temp1.right; temp2 = temp2.left; } return true; } }