对称二叉树
https://leetcode.cn/problems/symmetric-tree/
给你一个二叉树的根节点 root , 检查它是否轴对称。
1Solution BFS Accepted / Used 时空复杂度 O(n) O(n)
//用栈实现即可
class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
LinkedList<N> list = new LinkedList<>();
list.push(new N(1,root));
int max = 1;
N rt;
while(!list.isEmpty()) {
rt = list.pop();
if(rt.p.left!=null) {
max = Math.max(max,rt.val+1);
list.push(new N(rt.val+1,rt.p.left));
}
if(rt.p.right!=null) {
max = Math.max(max,rt.val+1);
list.push(new N(rt.val+1,rt.p.right));
}
}
return max;
}
}
class N {
int val;
TreeNode p;
public N() {}
public N(int val,TreeNode p) {
this.val = val;
this.p = p;
}
}
2 Solution DFS Accepted / Used 时空复杂度 O(n) O(height)
递归的含义:
max(l,r)+1,定义一个f(t),返回最大深度,每层都加一即可
height 表示最大深度,每层消耗O(1) 空间
class Solution {
static int f(TreeNode root) {
if(root==null) return 0;
return Math.max(f(root.left),f(root.right))+1;
}
public int maxDepth(TreeNode root) {
return f(root);
}
}
3 Solution BFS 官方版 Accepted / Used 时空复杂度 O(n) O(n)
递归的含义:
// <>BFS使用队列实现, 严格使用 list.add(), list.poll()
//<>DFS使用栈实现,严格使用 list.push(), list.pop()=
//<>BFS用到DFS的方法 或者 DFS用到BFS的方法 结果很容易出错
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
LinkedList<TreeNode> list = new LinkedList<>();
list.add(root);
int ans = 0, len = 0;
TreeNode nd;
while(!list.isEmpty()) {
len = list.size();//利用长度的也可以确定每一层有多少个节点,以此算出最大深度
for(int i = 0; i < len; ++i) {
nd = list.poll();
if (nd.left != null) list.add(nd.left);
if (nd.right != null) list.add(nd.right);
}
ans++;
}
return ans;
}
}