Java accepted solution 8ms


  • 0
    W

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

        List<String> res = new ArrayList<String>();
        Map<TreeNode, String> nodeMap = new HashMap<TreeNode, String>();
    
        if (null == root) return res;
        
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        nodeMap.put(root, String.valueOf(root.val));
        
        while(!stack.isEmpty()) {
            TreeNode node = stack.pop();
            
            if ((null == node.left) && (null == node.right)) {
                res.add(nodeMap.get(node));
            } 
            if (null != node.left) {
                stack.push(node.left);
                nodeMap.put(node.left, nodeMap.get(node)+"->" + String.valueOf(node.left.val));
            }
            if (null != node.right) {
                stack.push(node.right);
                nodeMap.put(node.right, nodeMap.get(node)+"->" + String.valueOf(node.right.val));
            }
            nodeMap.remove(node);
            
        }
        return res;
    }
    

    }


Log in to reply
 

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