Java Backtracing Solution


  • 0
    S
    public class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> result = new ArrayList();
            if(root==null){
                return result;
            }
            backtracing(result, String.valueOf(root.val), root);
            return result;
        }
        
        public void backtracing(List<String> result, String temps, TreeNode root){
            if(root == null){
                return;
            }
            if(root.left == null && root.right == null){
                result.add(temps);
                return;
            }
            if(root.left!=null){
                backtracing(result, temps+"->"+String.valueOf(root.left.val), root.left);
            }
            if(root.right!=null){
                backtracing(result, temps+"->"+String.valueOf(root.right.val), root.right);
            }
            
        }
    }

Log in to reply
 

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