后序遍历非递归,当遍历到叶子结点时,将栈中所有的内容都按照格式要求生成列表返回。
static List<String> ret=new ArrayList<>();//全局变量
static public List<String> binaryTreePaths(TreeNode root) {
// write your code here
if(root==null) return ret;
Stack<TreeNode> sta=new Stack<>();
TreeNode p=root;
TreeNode pre=null;//后序遍历非递归要用到一个pre指针
while(p!=null||!sta.isEmpty()){
if(p!=null)
{
sta.push(p);
p=p.left;
}
else {
p=sta.peek();//看一下最后一个节点的有节点有没有访问过
if(p.right!=null&&pre!=p.right){
p=p.right;
}
else{
p=sta.pop();
//处理栈中所有的数据
if(p.left==null&&p.right==null){
String a="";
for (TreeNode t:sta
) {
a=a+"->"+t.val;
}
a+="->"+p.val;
a=a.substring(2,a.length());
ret.add(a);
}
pre=p;
p=null;
}
}
}
return ret;
}