LintCode 480-二叉树的所有路径

来源:互联网 发布:58同城网络销售可靠吗 编辑:程序博客网 时间:2024/05/17 02:39

后序遍历非递归,当遍历到叶子结点时,将栈中所有的内容都按照格式要求生成列表返回。

 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;  }
原创粉丝点击