二叉树之深度和结点问题

1.二叉树的最小深度

Leetcode 111;easy;

package tree;

public class Main0111二叉树的最小深度 {
	public static void main(String[] args) {
		TreeNode root = new TreeNode(1);
		TreeNode node1 = new TreeNode(2);
		root.left = node1;
		int depth = new Solution111().minDepth(root);
		System.out.println(depth);
	}
}

// 最小深度:从根节点到最近叶子节点的最短路径上的节点数量。
class Solution111 {
	public int minDepth(TreeNode root) {
		if (root == null)
			return 0;
		if (root.left == null)
			return minDepth(root.right) + 1;
		if (root.right == null)
			return minDepth(root.left) + 1;
		return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
	}
}

2.二叉树的最大深度

Leetcode 104;easy;

package tree;

// 104最大深度、111最小深度、222结点个数
public class Main0104二叉树的最大深度 {
	public static void main(String[] args) {
		TreeNode root = new TreeNode(1);
		TreeNode node1 = new TreeNode(2);
		TreeNode node2 = new TreeNode(3);
		TreeNode node3 = new TreeNode(4);
		root.left = node1;
		root.right = node2;
		node1.left = node3;
		int depth = new Solution104().maxDepth(root);
		System.out.println(depth);
	}
}

class Solution104 {
	public int maxDepth(TreeNode root) {
		if (root == null)
			return 0;
		return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
	}
}

3.二叉树的结点个数

Leetcode 222;easy;

package tree;

import java.util.LinkedList;
import java.util.Queue;

public class Main0222完全二叉树的节点个数 {
	public static void main(String[] args) {
		TreeNode root = new TreeNode(1);
		TreeNode node = new TreeNode(1);
		TreeNode node1 = new TreeNode(1);
		root.left = node;
		node.left = node1;
		int nodes = new Solution222().countNodes(root);
		System.out.println(nodes);
	}
}

class Solution222 {
	public int countNodes(TreeNode root) {
		if (root == null)
			return 0;
		return countNodes(root.left) + countNodes(root.right) + 1;
	}
}

class Solution0222 {
	public int countNodes(TreeNode root) {
		if (root == null)
			return 0;

		Queue<TreeNode> queue = new LinkedList<>();
		queue.add(root);
		int count = 1;
		while (!queue.isEmpty()) {
			TreeNode cur = queue.remove();
			if (cur.left != null) {
				queue.add(cur.left);
				count++;
			}
			if (cur.right != null) {
				queue.add(cur.right);
				count++;
			}
		}
		return count;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值