如何实现二叉树的层次遍历算法?
- 内容介绍
- 文章标签
- 相关推荐
本文共计337个文字,预计阅读时间需要2分钟。
给您的二叉树根节点 +root+,返回其节点值的层序遍历。
输入:+root+=[3,9,20,null,null,15,7]输出:[[3],[9,20],[15,7]]
输入:+root+=[1]输出:[[1]]
给你二叉树的根节点root,返回其节点值的层序遍历。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
提示:
- 树中节点数目在范围
[0, 2000]内 -1000 <= Node.val <= 1000
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return cmp(root.left, root.right);
}
private boolean cmp(TreeNode node1, TreeNode node2) {
if (node1 == null && node2 == null) {
return true;
}
if (node1 == null || node2 == null || node1.val != node2.val) {
return false;
}
return cmp(node1.left, node2.right) && cmp(node1.right, node2.left);
}
}
本文共计337个文字,预计阅读时间需要2分钟。
给您的二叉树根节点 +root+,返回其节点值的层序遍历。
输入:+root+=[3,9,20,null,null,15,7]输出:[[3],[9,20],[15,7]]
输入:+root+=[1]输出:[[1]]
给你二叉树的根节点root,返回其节点值的层序遍历。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
提示:
- 树中节点数目在范围
[0, 2000]内 -1000 <= Node.val <= 1000
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return cmp(root.left, root.right);
}
private boolean cmp(TreeNode node1, TreeNode node2) {
if (node1 == null && node2 == null) {
return true;
}
if (node1 == null || node2 == null || node1.val != node2.val) {
return false;
}
return cmp(node1.left, node2.right) && cmp(node1.right, node2.left);
}
}

