JZ38 --- 二叉树的深度

题目描述:
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

题解:

题解一:
递归实现。

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

题解二:
利用队列来解决。
在出队之前,此时队列中记录的只有某一层节点,所以队列的大小就是某一层节点的个数。当此个数减到 0 的时候,则说明该层节点全部出队完成。

public int TreeDepth2(TreeNode root) {
    if (root == null) {
        return 0;
    }
    Queue<TreeNode> queue = new LinkedList<TreeNode> ();
    queue.add (root);
    int depth = 0;
    int size = -1;
    while (!queue.isEmpty()) {
        size = queue.size ();
        while (size != 0) {
            TreeNode node = queue.poll ();
            if (node.left != null) {
                queue.add (node.left);
            }
            if (node.right != null) {
                queue.add (node.right);
            }
            size--;
        }
        depth++;
    }
    return depth;
}

解法三:
层序遍历。需要一个list来存某一层的全部结点。

public int TreeDepth(TreeNode root) {
    if (root == null) {
        return 0;
    }
    ArrayList<TreeNode> list = new ArrayList<TreeNode> ();
    list.add (root);
    int depth = 0;
    while (list.size () != 0) {
        depth++;
        ArrayList<TreeNode> tmp = new ArrayList<> ();
        for (int i = 0; i < list.size (); i++) {
            while (list.get (i).left != null) {
                tmp.add (list.get (i).left);
            }
            while (list.get (i).right != null) {
                tmp.add (list.get (i).right);
            }
        }
        // list中存着一层结点
        list = tmp;
    }
    return depth;
}

你可能感兴趣的:(剑指offer)