[LeetCode] 101. 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.
给一个二叉树判断是否为对称树。
解法1: 非递归,按层遍历,每一层检查一下是否对称。
解法2: 递归,
其中左子树和右子树对称的条件:1)两个节点值相等,或者都为空。2)左节点的左子树和右节点的右子树对称,左节点的右子树和右节点的左子树对称
Java:Recursion
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 |
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isSymmetric(TreeNode root) { if(root == null) return true; return checkNodes(root.left, root.right); } private boolean checkNodes(TreeNode left, TreeNode right){ if(left == null && right == null) return true; if(left==null || right== null ) return false; if(left.val != right.val) return false; return checkNodes(left.left, right.right) && checkNodes(left.right, right.left); } } |
Java: Iteration
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 29 30 31 32 33 34 35 36 |
|