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 [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Follow up: Solve it both recursively and iteratively.

思路

此题判断一颗二叉树是否对称。分别采用递归和迭代解法实现。可假想有两颗树,分别按根、左、右和根、右、左来比较这两颗树是否相同即可。

Java实现

递归解法

/**
 * 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) {
        return check(root, root);
    }

    private boolean check(TreeNode r1, TreeNode r2) {
        if (r1 == null && r2 == null) {
            return true;
        }

        if (r1 == null || r2 == null) {
            return false;
        }

        return r1.val == r2.val && check(r1.left, r2.right) && check(r1.right, r2.left);

    }
}

迭代解法

/**
 * 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) {
        return check(root, root);
    }

    public boolean check(TreeNode r1, TreeNode r2) {
        Queue<TreeNode> q = new LinkedList<>();
        q.add(r1);
        q.add(r2);
        while (!q.isEmpty()) {
            r1 = q.poll();
            r2 = q.poll();
            if (r1 == null && r2 == null) {
                continue;
            }
            if (r1 == null || r2 == null || r1.val != r2.val) {
                return false;
            }
            q.add(r1.left);
            q.add(r2.right);
            q.add(r1.right);
            q.add(r2.left);
        }
        return true;
    }
}

Python实现

递归解法

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.check(root, root)

    def check(self, r1, r2):
        """
        :type r1: TreeNode
        :type r2: TreeNode
        :rtype: bool
        """
        if r1 is None and r2 is None:
            return True
        
        if r1 is None or r2 is None:
            return False
        
        return r1.val == r2.val and self.check(r1.left, r2.right) and self.check(r1.right, r2.left)
    

迭代解法

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.check(root, root)

    def check(self, r1, r2):
        """
        :type r1: TreeNode
        :type r2: TreeNode
        :rtype: bool
        """
        queue = []
        queue.append(r1)
        queue.append(r2)
        while len(queue) != 0:
            u = queue.pop(0)
            v = queue.pop(0)
            if u is None and v is None:
                continue
            
            if u is None or v is None or u.val != v.val:
                return False

            queue.append(u.left)
            queue.append(v.right)
            queue.append(u.right)
            queue.append(v.left)
        
        return True
    

Scala实现

递归解法

/**
 * Definition for a binary tree node.
 * class TreeNode(var _value: Int) {
 *   var value: Int = _value
 *   var left: TreeNode = null
 *   var right: TreeNode = null
 * }
 */
object Solution {
    def isSymmetric(root: TreeNode): Boolean = {
        return check(root, root)
    }
    
    def check(r1: TreeNode, r2: TreeNode): Boolean = {
        if (r1 == null && r2 == null) {
            return true
        }
        
        if (r1 == null || r2 == null) {
            return false
        }
        
        return r1.value == r2.value && check(r1.left, r2.right) && check(r1.right, r2.left)
    }
}

迭代解法

/**
 * Definition for a binary tree node.
 * class TreeNode(var _value: Int) {
 *   var value: Int = _value
 *   var left: TreeNode = null
 *   var right: TreeNode = null
 * }
 */
import scala.collection.mutable.Queue
import util.control.Breaks._

object Solution {
    def isSymmetric(root: TreeNode): Boolean = {
        return check(root, root)
    }
    
    def check(r1: TreeNode, r2: TreeNode): Boolean = {
        val queue = new Queue[TreeNode]()
        queue.enqueue(r1)
        queue.enqueue(r2)
        while (!queue.isEmpty) {
            val u = queue.dequeue()
            val v = queue.dequeue()
            breakable{
                if (u == null && v == null) {
                    break
                }
                if (u == null || v == null || u.value != v.value) {
                    return false
                }

                queue.enqueue(u.left)
                queue.enqueue(v.right)
                queue.enqueue(u.right)
                queue.enqueue(v.left)
            }
        }
        return true
    }
}

你可能感兴趣的:(LeetCode)