Java solutions without recursions, using a stack


  • 0
    D

    I simply do a DFS traversal with a stack, and I store current path in a list. Main point is to detect "way back" by pushing current node to stack if it is not the same as last entry in path.

       public List<String> binaryTreePaths(TreeNode root) {
            if(root == null){
                return Collections.emptyList();
            }
            List<String> res = new ArrayList<>();
            
            Deque<TreeNode> st = new ArrayDeque<>();
            Deque<TreeNode> path = new ArrayDeque<>();
            
            st.addFirst(root);
            while(!st.isEmpty()){
                root = st.removeFirst();
                if(root != path.peekLast()){
                    path.addLast(root);
                    st.addFirst(root);
                }
                else{
                    path.removeLast();
                    continue;
                }
                if(root.left == null && root.right == null){
                    Iterator<TreeNode> iter = path.iterator();
                    StringBuilder tmp = new StringBuilder(path.size() *3 - 2);
                    tmp.append(Integer.toString(iter.next().val));
                    while(iter.hasNext()){
                        tmp.append("->");
                        tmp.append(Integer.toString(iter.next().val));
                    }
                    res.add(tmp.toString());
                }
                if(root.left != null){
                    st.addFirst(root.left);
                }
                if(root.right != null){
                    st.addFirst(root.right);
                }
            }
            return res;
        }

  • 0
    Q

    My Simple Java Solution :

    public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {

        ArrayList<String> ret = new ArrayList<String>();
        String s = "";
        btPath(ret, root, s);
        return ret;
    }
    
    public void btPath(ArrayList<String> ret, TreeNode root, String s){
        if(root == null) return;
    
        s += String.valueOf(root.val);
        if(root.left ==  null && root.right == null){
            ret.add(s);
            return;
        }
        btPath(ret, root.left, s+"->");
        btPath(ret, root.right, s+"->");
        s.substring(0, s.length()-1);
        return;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.