1 public class Solution {
2 public int treeHeight(String preorder) {
3 if (preorder==null || preorder.length()==0) return -1;
4 preorder.trim();
5 if (preorder.length() == 0) return -1;
6 String[] ar = preorder.split(" ");
7 Stack st = new Stack();
8 int maxHeight = 0;
9 int curHeight = 0;
10 String root = ar[0];
11 int i = 0;
12 while (!root.equals("*") || !st.isEmpty()) {
13 if (!root.equals("*")) { // not null
14 st.push(root);
15 curHeight++; // this node's height
16 maxHeight = Math.max(maxHeight, curHeight); //all time heighest
17 root = ar[++i]; // next node in preorder tranversal
18 }
19 else {
20 st.pop();
21 if (ar[i-1].equals("*")) curHeight = st.size() + 1; //only a=="*" && a[i-1]=="*", curheight will change
22 root = ar[++i];
23 }
24 }
25 if (i != ar.length) return -1; // if not reaching the end of the preorder array, then the tree is not valid
26 return maxHeight;
27 }
28 }
第21行比较tricky, 解释如下,如果遇到两个星的情况如**,表示遇到叶子节点了,pop操作之后,下一个节点(假设叫x)一定是某个节点(假设叫y)的第一个右节点,而且节点y已经不在stack里了,刚被pop掉,所以当前curHeight更新为 stack.size()+1, 这个1就是加上节点y的一层