题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
思路一:最简单的方法 递归判断左右子树
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); } }
思路二:用栈来成对存储左右子树 并且取得时候成对取 这样就保证比较的是镜像元素
用queue队列来存取数据也可以
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; } }