leetcode解题之57. Binary Tree Paths&129. Sum Root to Leaf Numbers Java版 (二叉树路径)

来源:互联网 发布:外国文学杂志知乎 编辑:程序博客网 时间:2024/06/01 19:40

257. Binary Tree Paths

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

For example, given the following binary tree:

   1 /   \2     3 \  5

All root-to-leaf paths are:

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

找出所有跟结点到叶子结点的路径

public List<String> binaryTreePaths(TreeNode root) {List<String> list = new ArrayList<>();if (root == null)return list;dfsCore(root, list, "");return list;}private void dfsCore(TreeNode root, List<String> list, String s) {if (root == null)return;s += root.val;if (root.left == null && root.right == null)list.add(s);if (root.left != null)dfsCore(root.left, list, s + "->");if (root.right != null)dfsCore(root.right, list, s + "->");}
使用list,然后转化为结果。参考

public List<String> binaryTreePaths(TreeNode root) {List<String> list = new ArrayList<>();if (root == null)return list;List<List<Integer>> ret = new ArrayList<>();List<Integer> tmp = new ArrayList<>();dfs(root, ret, tmp);for (List<Integer> t : ret) {String s = "";for (int i = 0; i < t.size() - 1; i++) {s += t.get(i) + "->";}s += t.get(t.size() - 1);list.add(s);}return list;}private void dfs(TreeNode root, List<List<Integer>> ret, List<Integer> tmp) {if (root != null) {if (root.left == null && root.right == null) {tmp.add(root.val);ret.add(new ArrayList<>(tmp));tmp.remove(tmp.size() - 1);return;}//递归|回溯tmp.add(root.val);dfs(root.left, ret, tmp);dfs(root.right, ret, tmp);tmp.remove(tmp.size() - 1);}}

129. Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number123.

Find the total sum of all root-to-leaf numbers.

For example,

    1   / \  2   3

The root-to-leaf path 1->2 represents the number12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

使用DFS,打印和与上题类似,也可以找出所有路径然后,转换成整数计算。

public int sumNumbers(TreeNode root) {if (root == null)return 0;List<String> list = new ArrayList<>();sumCore(root, list, "");System.out.println(list);int res = 0;for (String s : list) {res += Integer.valueOf(s);}return res;}private void sumCore(TreeNode root, List<String> list, String s) {if (root != null) {if (root.left == null && root.right == null)list.add(s + root.val);sumCore(root.left, list, s + root.val);sumCore(root.right, list, s + root.val);}}
优化版:直接计算结果

public int sumNumbers(TreeNode root) {return helper(root, 0);}// 1.没有结点,2.有一个结点,3.多个结点private int helper(TreeNode root, int sum) {if (root != null) {// 2.有一个结点 // leafif (root.left == null && root.right == null)// 返回值!!!!return sum * 10 + root.val;// 3.多个结点 // left subtree + right subtreeint l = helper(root.left, sum * 10 + root.val);int r = helper(root.right, sum * 10 + root.val);return l + r;}// 1.没有结点return 0;}


0 0
原创粉丝点击