LeetCode 101: Symmetric Tree (Java)

来源:互联网 发布:淘宝双11数据 编辑:程序博客网 时间:2024/05/17 08:04

核心思想:递归判断左子树的右子树和右子树的左子树是否相同并且左子树的左子树和右子树的右子树是否相同。原函数只有一个参数,无法实现递归,所以增加一个有两个参数的函数。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isSymmetric(TreeNode root) {        if(root == null) return true;        return isSymmetricTwo(root.left, root.right);    }    public boolean isSymmetricTwo(TreeNode tree1, TreeNode tree2) {        if(tree1 == null && tree2 == null) return true;        if(tree1 == null || tree2 == null) return false;        if(tree1.val != tree2.val) return false;        return isSymmetricTwo(tree1.left, tree2.right) && isSymmetricTwo(tree1.right, tree2.left);    }}
0 0
原创粉丝点击