Java实现求二叉树的深度和宽度
这个是常见的对二叉树的操作。总结一下: 设节点的数据结构,如下: 复制代码 代码如下: class TreeNode { char val; TreeNode left = null; TreeNode right = null; TreeNode(char _val) { 1.二叉树深度 这个可以使用递归,分别求出左子树的深度、右子树的深度,两个深度的较大值+1即可。 复制代码 代码如下: // 获取最大深度 public static int getMaxDepth(TreeNode root) { if (root == null) return 0; else { int left = getMaxDepth(root.left); int right = getMaxDepth(root.right); return 1 + Math.max(left,right); } } 2.二叉树宽度 使用队列,层次遍历二叉树。在上一层遍历完成后,下一层的所有节点已经放到队列中,此时队列中的元素个数就是下一层的宽度。以此类推,依次遍历下一层即可求出二叉树的最大宽度。 复制代码 代码如下: // 获取最大宽度 public static int getMaxWidth(TreeNode root) { if (root == null) return 0; Queue<TreeNode> queue = new ArrayDeque<TreeNode>(); while (true) { (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |