统计一个ViewGroup中包含的子View的个数(递归和非递归实现)

问题:使用递归和非递归编码实现统计一个ViewGroup中所包含的子View的个数?

  • 首先大家想到的肯定是递归实现,简单且较容易想到,代码如下:
	/**
     * 递归统计一个View的子View数(包含自身)
     *
     * @param root
     * @return
     */
    public int count1(View root) {
        int viewCount = 0;

        if (null == root) {
            return 0;
        }

        if (root instanceof ViewGroup) {
            viewCount++;
            for (int i = 0; i < ((ViewGroup) root).getChildCount(); i++) {
                View view = ((ViewGroup) root).getChildAt(i);
                if (view instanceof ViewGroup) {
                    viewCount += count1(view);
                } else {
                    viewCount++;
                }
            }
        }

        return viewCount;
    }
  • 如果要求不用递归呢?那怎么实现呢?代码如下:
	/**
     * 非递归统计一个View的子View数(包含自身)
     *
     * @param root
     * @return
     */
    public int count(View root) {
        int viewCount = 0;

        if (null == root) {
            return 0;
        }

        if (root instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) root;
            LinkedList<ViewGroup> queue = new LinkedList<ViewGroup>();
            queue.add(viewGroup);
            while (!queue.isEmpty()) {
                ViewGroup current = queue.removeFirst();
                viewCount++;
                for (int i = 0; i < current.getChildCount(); i++) {
                    if (current.getChildAt(i) instanceof ViewGroup) {
                        queue.addLast((ViewGroup) current.getChildAt(i));
                    } else {
                        viewCount++;
                    }
                }
            }
        } else {
            viewCount++;
        }

        return viewCount;
    }

注释:非递归那就是树的广度优先遍历,每遍历到一个,计数器加一;

你可能感兴趣的:(算法,Android)