Finding max depth of binary tree without recursion

前端 未结 7 955
夕颜
夕颜 2020-12-24 09:23

Recursive mechanism to find max depth of depth of binary tree is very straightforward, but how can we do it efficiently without recursion as I have large tree where I would

7条回答
  •  情书的邮戳
    2020-12-24 09:56

    Another way is to use Level order traversal, where tree height is equal to the number of level of a tree. (It can only be use to calulate the minimal height of a tree.)

    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        LinkedList arr = new LinkedList(); // queue for current level
        LinkedList tmp = new LinkedList(); // queue for next level
        arr.add(root);
        int res = 0; // result
        TreeNode node; // tmp node 
        while (true) {
            while (!arr.isEmpty()) {
                node = arr.poll();
                if (node.left != null) tmp.add(node.left);
                if (node.right != null) tmp.add(node.right);
            }
            res++;
            if (tmp.isEmpty()) break;
            arr = tmp;
            tmp = new LinkedList();
        }
        return res;
    }
    

提交回复
热议问题