题意
对称树,判断一个树是否是对称的。
我的思想
首先避开第一个节点,对比它的左右树。采用先序遍历法遍历左树,后序遍历遍历右边的树对比
我的代码
递归实现的方法1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26/**
* 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||(root.left==null&&root.right==null))
return true;
return travelTree(root.left,root.right);
}
public boolean travelTree(TreeNode leftroot,TreeNode rightroot){
if(leftroot==null&&rightroot==null)
return true;
if(leftroot!=null&&rightroot!=null)
{
if(leftroot.val==rightroot.val)
return travelTree(leftroot.left,rightroot.right)&&travelTree(leftroot.right,rightroot.left);
}
return false;
}
}
大神代码
把前面第一个节点对左右树的判断融汇到了递归中!这样子会多遍历一遍root树。
学习了代码缩减的方法。一个return 直接写在if后面
1 | public class Solution { |
非递归实现的方法,使用了队列。
1 | public boolean isSymmetric(TreeNode root) { |
非递归实现的方法,使用了栈
1 | public boolean isSymmetric(TreeNode root) { |