leetcode 257 Binary Tree Paths

2204 단어 LeetCode
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

귀속 방법:
1. 귀속 중지 조건, 루트가 비어 있는지 여부, 잎 결점 여부
2. 귀속 과정
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List binaryTreePaths(TreeNode root) {
        List res = new ArrayList();
        
        if(root == null)
            return res;
        
        if(root.left == null && root.right == null){
            res.add(root.val + "");
            return res;
        }
        
        List leftS = binaryTreePaths(root.left);
        for(int i=0;i" + leftS.get(i));
        }
        List rightS = binaryTreePaths(root.right);
        for(int i=0;i" + rightS.get(i));
        }
        
        return res;
    }
}

Submission에서 DFS 우선 순위:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    public List binaryTreePaths(TreeNode root) {
        List result = new LinkedList<>();
        dfs(result, root, "");
        return result;
    }
    
    private void dfs(List result, TreeNode node, String s) {
        if (node == null) return;
        String built = s.length() == 0 ? s + node.val : s + "->" + node.val;
        if (node.left == null && node.right == null) {
            result.add(built);
        } else {
            dfs(result, node.left, built);
            dfs(result, node.right, built);
        }
    }

}

좋은 웹페이지 즐겨찾기