Finding max depth of binary tree without recursion

前端 未结 7 901
夕颜
夕颜 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<TreeNode> arr = new LinkedList<TreeNode>(); // queue for current level
        LinkedList<TreeNode> tmp = new LinkedList<TreeNode>(); // 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<TreeNode>();
        }
        return res;
    }
    
    0 讨论(0)
提交回复
热议问题