LeetCode irregular brush title --Symmetric Tree

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

Note:
Bonus points if you could solve it both recursively and iteratively.

Solution:

/**
 * 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 isMirror(root.left,root.right);
        }
        return true;
    }
    public boolean isMirror(TreeNode r1,TreeNode r2){
        if(r1==null&&r2==null){
            return true;
        }
        if(r1==null||r2==null){
            return false;
        }
        if(r1.val==r2.val){
            return isMirror(r1.left,r2.right)&&isMirror(r1.right,r2.left);
        }
        return false;
    }
}

Determine whether a number is symmetric, we need to compare two nodes, and the declaration of a isMirror method to determine the left and right node are empty, or about a node is empty, we only excluded r1, r2 is empty case before they can be r1, r2 comparison value, or a null pointer exception will be reported. When a node is about equal to the value of time, we continue to the bottom of the recursive call isMirror method to arrive at the answer

Published 173 original articles · won praise 110 · Views 100,000 +

Guess you like

Origin blog.csdn.net/qq_35564813/article/details/104737014