Symmetric Tree
给一个二叉树, 看它左右两边是不是镜像的. 需要先观察一下镜像的概念, 就是翻转. 那么肯定需要递归的比较左右的node.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isSymmetric(TreeNode root) { if(root == null) return true; return isSymmetric(root.left,root.right); } public boolean isSymmetric(TreeNode l, TreeNode r) { if(l == null && r == null) return true; if(l == null || r == null) return false; if(l.val == r.val) return isSymmetric(l.left,r.right) && isSymmetric(l.right,r.left); else return false; } } |