赞
踩
尝试不同方法求二叉树的深度:
1.depth1,递归计算二叉树的深度,根结点的深度=max(左子树的深度,右子树的深度) + 1。
2.depth2,访问左结点,如有右结点则压栈1,同时把右结点的深度压栈2,没有左结点时表示该次遍历完成,记录深度;从栈1取出结点,栈2取出该结点的深度,再次遍历。
3.depth3,利用层序遍历的思想,每完成一层的遍历就给一个标记。
package com.devchao.tree;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class BinaryTree {
public static void main(String[] args) {
Node n15 = new Node(15, null, null);
Node n14 = new Node(14, n15, null);
Node n13 = new Node(13, null, n14);
Node n12 = new Node(12, n13, null);
Node n11 = new Node(11, null, n12);
Node n5 = new Node(5, null, null);
Node n6 = new Node(6, null, null);
Node n8 = new Node(8, null, null);
Node n9 &
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。