问道Pocket Gems面试题

原帖地址:mitbbs

题在这儿
http://yuanhsh.iteye.com/blog/2206191

我的解法和博客里的有点不同,不知道有没有忘记考虑什么case,有谁愿意帮我看一下
吗?谢谢!
import java.util.Stack;

public class Solution {
public TreeNode ternary2Tree(String ternary) {
if (ternary.length() == 0) {
return null;
}

Stack stack = new Stack<>();
TreeNode root = new TreeNode(ternary.charAt(0));
stack.push(root);

for (int i = 1; i < ternary.length(); i += 2) { char operator = ternary.charAt(i); TreeNode node = new TreeNode(ternary.charAt(i + 1)); if (operator == '?') { stack.peek().left = node; } else { stack.pop(); stack.pop().right = node; } stack.push(node); } return root; } }