递归算法分析:
- 创建check递归函数,用于检查两个树是否相同
- 调用check时,对称比较 eg.传入左子树的左子树和右子树的右子树对比
代码:
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public boolean checkSymmetricTree(TreeNode left_tree, TreeNode right_tree){if(left_tree == null && right_tree == null){return true;}if(left_tree == null || right_tree == null){return false;}return left_tree.val == right_tree.val && (checkSymmetricTree(left_tree.left, right_tree.right) && checkSymmetricTree(left_tree.right, right_tree.left));}public boolean isSymmetric(TreeNode root) {return checkSymmetricTree(root.left, root.right);}
}