来源:https://leetcode.com/problems/symmetric-tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / 2 2 / / 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / 2 2 3 3
递归:
1. 若根节点为null,返回true
2. 若根节点不为null,对其左右子树进行递归地比较:若两个节点都为null,返回true;若一个为null,另一个不为null,返回false;若两个节点(A,B)值相等,则返回 (A.left, B.right) 的比较结果 && (A.right, B.left) 的比较结果。
Java
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public boolean compareLR(TreeNode left, TreeNode right) { 12 if(left == null && right == null) { 13 return true; 14 } 15 if((left == null && right != null) || (left != null && right == null)) { 16 return false; 17 } 18 if(left.val == right.val) { 19 return compareLR(left.right, right.left) && compareLR(left.left, right.right); 20 } 21 return false; 22 } 23 public boolean isSymmetric(TreeNode root) { 24 if(root == null) { 25 return true; 26 } 27 return compareLR(root.left, root.right); 28 } 29 }
Python
1 # -*- coding:utf-8 -*- 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 class Solution: 8 def isSymmetrical(self, pRoot): 9 def comRoot(left, right): 10 if not left: 11 return not right 12 if not right or (left.val != right.val): 13 return False 14 return comRoot(left.right, right.left) and comRoot(left.left, right.right) 15 if not pRoot: 16 return True 17 return comRoot(pRoot.left, pRoot.right)
迭代:
1. 若根节点为null,返回true
2. 若根节点不为null,将其左右两个子节点入队列
3. 从队列中取出两个节点,若两个节点都为null,返回true;若一个为null,另一个不为null,返回false;若两个节点(A,B)值相等,将他们的两个子节点按照A.left,B.right,A.right,B.left的顺序入队列,重复执行该步,直到队列中不再有节点。