My Accepted solution Iterative

  • 0
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
    class Solution {
        //1. LookUp table to store parent and child,
        // lookUp(childNode, parentNode)
        Map<TreeNode,TreeNode> lookUp = new HashMap<>();
        //2. Result will be store in the following list
        List<String> res = new ArrayList<>();
        //3. StringBuilder to build a result on the fly
         StringBuilder sb = new StringBuilder();
        public List<String> binaryTreePaths(TreeNode root) {
            //1. If root is null, return an empty collection
            if(root == null)    return res;
            //2. Iterative preorder traversal - stack instantiation
            Deque<TreeNode> stack = new ArrayDeque<>();
            //2.a push root and mark parent of root as null in map
            //2.b start preoder traversal
                root = stack.pop();
                //2.c If children are null then the node is leaf, call method to prepare result
                if(root.left == null && root.right == null) {
                //2.d  Right node is pushed, as we need to print result of left node first
                // also map the child to parent
                if(root.right != null) {
                //2.e Left node is pushed and mapped child to parent
                if(root.left != null){
            return res;
        // Method to create an item for the collection
        public void addResult(TreeNode root){
            // Temporary stack to store the result
            Deque<TreeNode> temp_Stack = new ArrayDeque<>();
            // load the stack by looking up parents
            while(root != null){
                 root = lookUp.get(root);
            // unload the stack and prepare the result using stringBuilder
                root = temp_Stack.pop();
                sb = temp_Stack.isEmpty() ? sb.append(root.val) :sb.append(root.val).append("->");
            // Add the prepared item into collection
            // Instantiate a new StringBuilder instance for future use,
            sb = new StringBuilder();

    thanks to GeeksforGeeks for the algorithm

Log in to reply

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