本文主要是介绍判断一棵二叉树是否为对称树之java实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
package com.cb.java.algorithms.jianzhioffer.tree;public class SymmetricTree {class TreeNode {int data; // 数据域TreeNode left;// 左子节点TreeNode right; // 右子节点public TreeNode(int data) {this.data = data;}}public boolean isSymmetric(TreeNode root) {// 树为空,则返回trueif (root == null)return true;elsereturn isSame(root.left, root.right);}private boolean isSame(TreeNode left, TreeNode right) {// 做右子节点都为空if (left == null && right == null)return true;else if (left == null || right == null)return false;// 左右子节点不为空则分别判断左右子树if (left != null && right != null) {return left.data == right.data && isSame(left.left, right.right) && isSame(left.right, right.left);}return false;}
}
这篇关于判断一棵二叉树是否为对称树之java实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!