# Android 布局横向遍历，深度求解

2018/01/20 22:17

## 一、二叉树的横向遍历

import java.util.ArrayList;
import java.util.List;

public class MainTest {

public static void main(String[] args) {

Node treeNode = buildTree();
printTree(treeNode);
}

public static  void printTree(Node node)
{
if(node==null);
List<Node[]> nodeList = new ArrayList<Node[]>();
Node[] nodes = new Node[]{node};
System.out.print(node.name);
while(nodes!=null && nodes.length>0){
nodes = getChildNodes(nodes);
for (int i = 0; i < nodes.length; i++) {
Node n = nodes[i];
if(n!=null)
{
System.out.print("-->"+n.name);
}
}
}
}

public static Node[] getChildNodes(Node[] nodes)
{
if(nodes==null) return null;
List<Node> lst = new ArrayList<Node>();
for (int i = 0; i < nodes.length; i++) {
Node node = nodes[i];
if(node.left!=null)
{
}
if(node.right!=null)
{
}
}
Node[] nodeChildren = new Node[lst.size()];
lst.toArray(nodeChildren);
return nodeChildren;

}

public static Node buildTree()
{
Node root = new Node("A");
root.left = new Node("B");
root.right = new Node("C");
root.left.left = new Node("D");

root.right.left = new Node("E");
root.right.right = new Node("F");

return root;
}
}

class Node{
public Node left;
Public Node right;
public String name;
public Node(String name)
{
this.name = name;
}
}

## 二、求二叉树的深度

int treeDepth(Node root){
if(root==null){
return 0;
}
int nLeft=treeDepth(root.left);
int nRight=treeDepth(root.right);

return nLeft>nRight?nLeft+1:nRight+1;
}

android 打印布局深度

  /**
* 打印View嵌套层数
*
* @param root
* @return
*/
public static int getViewTreeDepth(View root) {
if (root == null) return 0;
if (root instanceof ViewGroup) {
final ViewGroup parent = (ViewGroup) root;

final int count = ((ViewGroup) root).getChildCount();
if (count == 0) return 1;
int maxDeepth = 0;
for (int i = 0; i < count; i++) {
maxDeepth = Math.max(getViewTreeDepth(parent.getChildAt(i)), maxDeepth);
}
return maxDeepth + 1;

} else {
return 1;
}

}

public int getViewTreeDepth(View view){

if(view==null) return 0;
if(!(view instanceof ViewGroup)) return 1;
ViewGroup group = (ViewGroup) view;

List<ViewGroup> childQueue = new ArrayList<>();
queue.offer(group);
int deep = 1;

while (!queue.isEmpty()){

while(!queue.isEmpty())
{
ViewGroup groupNode = queue.poll();
int childCount = groupNode.getChildCount();
for (int i=0;i<childCount;i++){
View child = groupNode.getChildAt(i);
if(child instanceof ViewGroup){
}
}
}

deep++;
if(childQueue.size()>0) {
childQueue.clear();
}

}
return deep;
}
}

    public static View getMaxDepthLeafView(View root) {
if (!(root instanceof ViewGroup)) return root;
queue.offer(root);
View view = null;
while (queue.size() > 0) {
view = queue.poll();
if ((view instanceof ViewGroup)) {
final ViewGroup viewGroup = (ViewGroup) view;
final int count = viewGroup.getChildCount();
for (int i = 0; i < count; i++) {
queue.offer(viewGroup.getChildAt(i));
}
}
}
return view;
}

0 评论
0 收藏
0