# 257 Binary Tree Paths

給一棵Binary Tree,印出所有root-leaf paths

  • Idea: 蠻單純的,recursive dfs
  • Code:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        List<String> res = new ArrayList<>();
        public List<String> binaryTreePaths(TreeNode root) {
            /*
            dfs each branch(stack), record as string
            */
            if(root == null) return res;
            int val = root.val;
            dfs(root, ""+val);
            return res;
        }
    
        void dfs(TreeNode n, String s){
            if(n.right == null && n.left == null){
                res.add(s);
                return;
            }
            if(n.right != null) dfs(n.right, s+"->"+n.right.val);
            if(n.left != null) dfs(n.left, s+"->"+n.left.val);
        }
    
    }
    

results matching ""

    No results matching ""