求二叉树的深度和宽度[Java]

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

设节点的数据结构,如下:

1 class TreeNode {
2     char val;
3     TreeNode left = null;
4     TreeNode right = null;
5 
6     TreeNode(char _val) {
7         this.val = _val;
8     }
9 }

 1.二叉树深度

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

 1     // 获取最大深度
 2     public static int getMaxDepth(TreeNode root) {
 3         if (root == null)
 4             return 0;
 5         else {
 6             int left = getMaxDepth(root.left);
 7             int right = getMaxDepth(root.right);
 8             return 1 + Math.max(left, right);
 9         }
10     }

2.二叉树宽度

  使用队列,层次遍历二叉树。在上一层遍历完成后,下一层的所有节点已经放到队列中,此时队列中的元素个数就是下一层的宽度。以此类推,依次遍历下一层即可求出二叉树的最大宽度。

 1 // 获取最大宽度
 2     public static int getMaxWidth(TreeNode root) {
 3         if (root == null)
 4             return 0;
 5 
 6         Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
 7         int maxWitdth = 1; // 最大宽度
 8         queue.add(root); // 入队
 9 
10         while (true) {
11             int len = queue.size(); // 当前层的节点个数
12             if (len == 0)
13                 break;
14             while (len > 0) {// 如果当前层,还有节点
15                 TreeNode t = queue.poll();
16                 len--;
17                 if (t.left != null)
18                     queue.add(t.left); // 下一层节点入队
19                 if (t.right != null)
20                     queue.add(t.right);// 下一层节点入队
21             }
22             maxWitdth = Math.max(maxWitdth, queue.size());
23         }
24         return maxWitdth;
25     }

 

参考:http://blog.csdn.net/htyurencaotang/article/details/12406223

posted on 2014-10-20 13:51  旭东的博客  阅读(41230)  评论(0编辑  收藏  举报

导航