import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int data) {
this.val = data;
}
}
//在二叉树中寻找一个节点,判断是第几层第几个
public static void findNodeInlevelIndex(TreeNode pRoot, int k) {
int level = 1;
Queue<TreeNode> layer = new LinkedList<TreeNode>();
ArrayList<Integer> layerList = new ArrayList<Integer>();
layer.add(pRoot);
int start = 0, end = 1;
while (!layer.isEmpty()) {
TreeNode cur = layer.remove();
if(cur.val==k){
System.out.println("层数是"+level+",下标是"+(start+1));
}
layerList.add(cur.val);
start++;
if (cur.left != null) {
layer.add(cur.left);
}
if (cur.right != null) {
layer.add(cur.right);
}
if (start == end) {
end = layer.size();
start = 0;
layerList = new ArrayList<Integer>();
level++;
}
}
}
public static void main(String[] args) {
TreeNode head = new TreeNode(1);
head.left = new TreeNode(2);
head.right = new TreeNode(3);
head.left.left = new TreeNode(4);
head.left.right = new TreeNode(5);
head.right.left = new TreeNode(6);
head.right.right = new TreeNode(7);
findNodeInlevelIndex(head,3);
}
}