题目链接: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 is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
思路:
注意我在递归中保存结果的方式,跟Kth Smallest Element in a BST 算法2和Balanced Binary Tree 中是一样的。
基本框架是:
boolean result = true; public boolean recur(TreeNode root){ if(root!=null){ if(satisfy a condition){ result = false; } recur(root.left); recur(root.right); } return result; }
算法:
public boolean isSym(TreeNode p, TreeNode q) { if (p == null && q == null) {//都为空 return true; }else if (p == null || q == null) {//有一个不为空 result = false; }else if (p.val == q.val) { isSym(p.left, q.right);//注意对称 isSym(p.right, q.left); } else { result = false; } return result; } public boolean isSymmetric(TreeNode root) { if (root == null) { return true; } if (root.left == null && root.right == null) { //单结点 return true; } if (root.left == null || root.right == null) {//不对称 return false; } return isSym(root.left, root.right); } boolean result = true;