一开始想要层序遍历二叉树,然后判断每一层是否回文,写着写着发现这样太麻烦了,看了评论区别人的递归解法,才写出来的。
二叉树的四种遍历方法:
/d/file/titlepic/11229170.html class TreeNode { public int data; public TreeNode leftChild; public TreeNode rightChild; public TreeNode(int data){ this.data = data; }}public static void levelOrder(TreeNode root){ Li早中晚健康饮食习惯nkedList<TreeNode> queue = new LinkedList<>(); queue.add(root); while(!queue.isEmpty()){ root = queue.pop(); System.out.print(root.data+" "); if(root.leftChild!=null) queue.add(root.leftChild); if(root.rightChild!=null) queue.add(root.rightChild); }}
// Definition for a binary tree node.class TreeNode 边走边看{ int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } @Override public String toString() { return "" + val; }}class Solution { // 测试用例 // 1 // / \ // 2 2 // / \ / \ // 3 4 4 3 public static void main(String[] args) { Solution solution = new Solution(); TreeNode n1 = new TreeNode(1); TreeNode n21 = new TreeNode(2); TreeNode n22淄博驾校模拟考试 = new TreeNode(2邀请信怎么写); TreeNode n31 = new TreeNode(3); TreeNode n32 = new TreeNode(4); TreeNode n33 = new TreeNode(4); TreeNode n34 = ne英语四级作文万能句型w TreeNode(3); n1.left = n21; n1.right = n22; n21.left = n31; n21.right = n32; n22.left = n33; n22.right = n34; boolean res = solution.isSymmetric(n1); System.out.println(res); } public boolean isSymmetric(TreeNode root) { if (root == null) { return true; } el { return is(root.left, root.right); } } private boolean is(TreeNode n1, TreeNode n2) { if (n1 == null || n2 == null) { return n1 == n2; } el { return n1.val == n2.val && is(n1.left, n2.right) && is(n1.right, n2.left); } }}
本文地址:https://blog.csdn.net/sinat_42483341/article/details/107282454
本文发布于:2023-04-07 11:39:50,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/e417d4bff64f83552fc091102354601a.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:leetcode 101. 对称二叉树 递归解法.doc
本文 PDF 下载地址:leetcode 101. 对称二叉树 递归解法.pdf
留言与评论(共有 0 条评论) |