二叉树的深度 java

这个是常见的对二叉树的操作。总结一下:

数的结构:

public class TreeNode {
	int val;
	TreeNode left;
	TreeNode right;

	TreeNode(int x) {
		val = x;
	}
}

 1.二叉树深度

  这个可以使用递归,分别求出左子树的深度、右子树的深度,两个深度的较大值+1即可。

package niuke.easy;

public class GetMaxDepth {

	public static void main(String[] args) {

	}

	public int TreeDepth(TreeNode pRoot) {

		if (pRoot == null)
			return 0;
		int leftDepth = TreeDepth(pRoot.left);
		int rightDepth = TreeDepth(pRoot.right);

		return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
	}
}


### 计算二叉树深度的方法 #### 递归方法 通过递归方式计算二叉树深度是一种直观且简洁的方式。其核心思想是从根节点出发,分别递归地获取左子树和右子树的最大深度,并取两者中的较大值加一作为当前节点的高度。 以下是基于递归实现的代码示例: ```java public int treeDepthRecursive(Node root) { if (root == null) { return 0; } int leftDepth = treeDepthRecursive(root.left); int rightDepth = treeDepthRecursive(root.right); return Math.max(leftDepth, rightDepth) + 1; // 取左右子树最大深度并加上当前层高度 } ``` 上述代码展示了如何利用递归来求解二叉树深度[^1]。 --- #### 非递归方法 非递归方法通常借助栈或者队列来模拟递归过程。对于深度优先搜索(DFS),可以使用显式的栈结构;而对于层次遍历,则可以通过队列完成广度优先搜索(BFS)。 ##### 使用栈的非递归实现 该方法模仿前序遍历的过程,在访问每个节点的同时记录当前路径上的层数。 ```java public int treeDepthIterativeStack(Node root) { if (root == null) { return 0; } Stack<Node> stack = new Stack<>(); Stack<Integer> depthStack = new Stack<>(); stack.push(root); depthStack.push(1); int maxDepth = 0; while (!stack.isEmpty()) { Node node = stack.pop(); int currentDepth = depthStack.pop(); if (node != null) { maxDepth = Math.max(maxDepth, currentDepth); if (node.left != null) { stack.push(node.left); depthStack.push(currentDepth + 1); } if (node.right != null) { stack.push(node.right); depthStack.push(currentDepth + 1); } } } return maxDepth; } ``` 此部分描述了如何采用迭代法配合栈数据结构来解决相同问题[^2]。 --- ##### 基于队列的非递归实现 另一种常见的做法是运用队列执行逐层扫描操作,每处理一层就增加计数值直到最后一层结束为止。 ```java import java.util.LinkedList; import java.util.Queue; public int treeDepthLevelOrderTraversal(Node root) { if (root == null) { return 0; } Queue<Node> queue = new LinkedList<>(); queue.offer(root); int levelCount = 0; while (!queue.isEmpty()) { int size = queue.size(); // 当前层节点数量 for (int i = 0; i < size; ++i) { Node currentNode = queue.poll(); if (currentNode.left != null) { queue.offer(currentNode.left); } if (currentNode.right != null) { queue.offer(currentNode.right); } } levelCount++; // 完成一层后更新深度 } return levelCount; } ``` 这里提供了另外一种思路即通过队列来进行宽度优先搜索从而得到最终的结果[^3]。 --- ### 总结 无论是采取何种策略——递归还是非递归形式都可以有效地得出目标答案只是具体应用场景下各有优劣需视实际情况而定。如果追求简单明了则推荐前者反之后者可能更适合那些希望减少函数调用开销的情形下的开发者们考虑选用后者[^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值