Symmetrical binary tree - prove safety offer

Title Description

Please implement a function, a binary tree is used to determine not symmetrical. Note that if a binary image is a binary tree with this same definition as symmetrical.
 
An idea: the simplest method recursively determines left and right subtrees
public class Solution {
    boolean isSymmetrical(TreeNode pRoot)
    {
        if(pRoot == null) {
            return true;
        }
        return judge(pRoot.left,pRoot.right);
    }

    private boolean judge(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 judge(left.left,right.right) && judge(left.right,right.left);
    }
}

Two ideas: a stack to store the pair of left and right subtrees and thus obtain assurance when taken in pairs are mirror element comparison

A queue may be a queue to access data

import java.util.Stack;
public class Solution {
    boolean isSymmetrical(TreeNode pRoot)
    {
        if(pRoot == null) return true;
        Stack<TreeNode> stack=new Stack<>();
        stack.push(pRoot.left);
        stack.push(pRoot.right);
        while (!stack.isEmpty()){
            TreeNode right=stack.pop();
            TreeNode left=stack.pop();
            if(left == null && right == null) continue;
            if(left == null || right == null) return false;
            if(left.val != right.val) return false;
            stack.push(left.left);
            stack.push(right.right);
            stack.push(left.right);
            stack.push(right.left);
        }
        return true;
    }
}

 

Guess you like

Origin www.cnblogs.com/nlw-blog/p/12466807.html