[LeetCode] 101. Symmetric Tree
Given the root
of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:
Input: root = [1,2,2,3,4,4,3] Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3] Output: false
Constraints:
- The number of nodes in the tree is in the range
[1, 1000]
. -100 <= Node.val <= 100
Follow up: Could you solve it both recursively and iteratively?
对称二叉树。
给你一个二叉树的根节点 root
, 检查它是否轴对称。
题目很简单,跟100题几乎一样,也是用DFS思路做。唯一不同的地方是当判断子树的时候,100题是判断left.left == right.left;而这题是判断left.right == right.left
时间O(n)
空间O(n)
JavaScript实现
1 /** 2 * @param {TreeNode} root 3 * @return {boolean} 4 */ 5 var isSymmetric = function (root) { 6 if (root === null) { 7 return true; 8 } 9 return helper(root.left, root.right); 10 }; 11 12 var helper = function (left, right) { 13 if (left === null && right === null) { 14 return true; 15 } 16 if (left === null || right === null) { 17 return false; 18 } 19 if (left.val !== right.val) { 20 return false; 21 } 22 return helper(left.left, right.right) && helper(left.right, right.left); 23 };
Java实现
1 class Solution { 2 public boolean isSymmetric(TreeNode root) { 3 // corner case 4 if (root == null) { 5 return true; 6 } 7 return helper(root.left, root.right); 8 } 9 10 private boolean helper(TreeNode left, TreeNode right) { 11 if (left == null && right == null) { 12 return true; 13 } 14 if (left == null || right == null) { 15 return false; 16 } 17 if (left.val == right.val) { 18 return helper(left.left, right.right) && helper(left.right, right.left); 19 } else { 20 return false; 21 } 22 } 23 }