[LeetCode] 101. Symmetric Tree 对称树

[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

class Solution {

    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;

        LinkedList<TreeNode> q1 = new LinkedList<TreeNode>();

        LinkedList<TreeNode> q2 = new LinkedList<TreeNode>();

        q1.add(root.left);

        q2.add(root.right);

        while(!q1.isEmpty() && !q2.isEmpty()){

            TreeNode n1 = q1.poll();

            TreeNode n2 = q2.poll();

            if(n1.val != n2.val)

                return false;

            if((n1.left == null && n2.right != null) || (n1.left != null && n2.right == null))

                return false;

            if((n1.right == null && n2.left != null) || (n1.right != null && n2.left == null))

                return false;

            if(n1.left != null && n2.right != null){

                q1.add(n1.left);

                q2.add(n2.right);

            }

            if(n1.right != null && n2.left != null){

                q1.add(n1.right);

                q2.add(n2.left);

            }           

        }

        return true;

    }

}  

发布了900 篇原创文章 · 获赞 387 · 访问量 279万+

猜你喜欢

转载自blog.csdn.net/kingmax54212008/article/details/103828637