public void visitNode(TreeNode node, Bean bean) {
if (node == null) {
return;
}
bean.num++;
visitNode(node.left, bean);
visitNode(node.right, bean);
}
private void visitBFS(Queue<TreeNode> src) {
if (src.isEmpty()) {
return;
}
Queue<TreeNode> tar = new ArrayDeque<>();
while (!src.isEmpty()) {
TreeNode node = src.poll();
LogUtil.Companion.d(node.val);
if (node.left != null) {
tar.add(node.left);
}
if (node.right != null) {
tar.add(node.right);
}
}
visitBFS(tar);
}
public class DepthOfBinaryTree {
public void test() {
int min = minDepth(BinaryTreeUtil.prepareANode2());
int max = maxDepth(BinaryTreeUtil.prepareANode2());
LogUtil.Companion.d("min->" + min);
LogUtil.Companion.d("max->" + max);
}
int max;
public int maxDepth(TreeNode root) {
visitMaxNode(root, 1);
return max;
}
private void visitMaxNode(TreeNode node, int deep) {
if (node == null) {
return;
}
if (node.left == null && node.right == null) {
//说明是叶子节点
if (deep > max) {
max = deep;
}
}
visitMaxNode(node.left, deep + 1);
visitMaxNode(node.right, deep + 1);
}
int min = 0;
public int minDepth(TreeNode root) {
visitMinNode(root, 1);
return min;
}
private void visitMinNode(TreeNode node, int deep) {
if (node == null) {
return;
}
if (node.left == null && node.right == null) {
//说明是叶子节点
if (min == 0) {
min = deep;
}
if (deep < min) {
min = deep;
}
}
visitMinNode(node.left, deep + 1);
visitMinNode(node.right, deep + 1);
}
}
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
return dfs(root.left, root.right);
}
public boolean dfs(TreeNode left, TreeNode right) {
if (left == null || right == null) return left == right;
if (left.val != right.val) return false;
return dfs(left.left, right.right) && dfs(left.right, right.left);
}
网友评论