Leetcode学习笔记:#257. Binary Tree Paths

    xiaoxiao2025-01-15  16

    Leetcode学习笔记:#257. Binary Tree Paths.

    Given a binary tree, return all root-to-leaf paths.

    Note: A leaf is a node with no children.

    实现:

    public List<String> binaryTreePaths(TreeNode root){ List<String> answer = new ArrayList<String>)(); if(root != null) searchBT(root, "", answer); return answer; } pulibc void searchBT(TreeNode root, Sting path, List<String> answer){ if(root.left == null && root.right == null) answer.add(path + root.val); if(root.left != null)searchBT(root.left, path+root.val+"->", answer); if(root.right != null)searchBT(root.right, path+root.val+"->",answer); }

    思路: 前序遍历二叉树,非空节点判断是否拥有子节点,若有则进入下次递归

    最新回复(0)