剑指Offer——对称的二叉树

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_30281559/article/details/90677263

题目描述

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

递归方法:

public class Solution {
    boolean isSymmetrical(TreeNode pRoot)
    {
        if(pRoot == null) return true;
        return isEqual(pRoot.left,pRoot.right);
    }
    boolean isEqual(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 isEqual(left.left,right.right)&&isEqual(left.right,right.left);
    }
}

非递归方法:

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(right == null && left == 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;
    }
}
展开阅读全文

没有更多推荐了,返回首页