Simple Java Solution Beats 92.38%, StringBuilder, Pre-Order Traversal


  • 1
    J

    Save the path to the current node using StringBuilder. Traverse the tree in pre-order. Delete the current node from StringBuilder when leaving this node.

    public class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> list = new ArrayList<>();
            StringBuilder sb = new StringBuilder();
            
            preorder(root,list,sb);
            return list;
        }
        
        private void preorder(TreeNode node, List<String> list, StringBuilder sb) {
            if(node == null) return;
            int origin = sb.length();
            
            sb.append(node.val + "->");
            if(node.left == null && node.right == null)
                list.add(sb.substring(0,sb.length() - 2));
            else {
                preorder(node.left,list,sb);
                preorder(node.right,list,sb);
            }
            sb.delete(origin,sb.length());
        }
    }
    

    Run time: 16ms.


Log in to reply
 

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