101. 对称二叉树

一种递归技巧,两个变量向下递归

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public boolean isSymmetric(TreeNode root) {
  18. if (root == null) return true;
  19. return dfs(root.left, root.right);
  20. }
  21. boolean dfs(TreeNode l, TreeNode r) {
  22. if (l == null && r == null) return true;
  23. if (l == null || r == null) return false;
  24. if (l.val != r.val) return false;
  25. boolean res = true;
  26. res &= dfs(l.left, r.right);
  27. res &= dfs(l.right, r.left);
  28. return res;
  29. }
  30. }