您的位置:首页 > 其它

Binary Tree Paths

2015-10-22 22:26 204 查看
输出二叉树的寻叶路径
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"]

遍历二叉树的时候,每当寻到叶结点,把路径装进结果里

package com.rust.datastruct;

import java.util.ArrayList;
import java.util.List;

/**
* judging
* 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"]
*/
class BinaryTreePathsSolution {
List<String> res = new ArrayList<String>();
public List<String> binaryTreePaths(TreeNode root) {
if (root != null) track(root, root.val + "");/* String.valueOf(root.val)*/
return res;
}
private void track(TreeNode n, String path){
if (n.left == null && n.right == null) res.add(path);
if (n.left != null) track(n.left, path + "->" + n.left.val);/* continue tracking */
if (n.right != null) track(n.right, path + "->" + n.right.val);
}
}

/**
* Test main
*/
public class BinaryTreePaths {
public static void main(String args[]) {
TreeNode root = new TreeNode(0);
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(4);
TreeNode node5 = new TreeNode(5);
TreeNode node6 = new TreeNode(6);
TreeNode node7 = new TreeNode(7);

root.left = node1;
root.right = node2;
node1.left = node3;
node1.right = node4;
node2.left = node5;
node2.right = node6;
node4.right = node7;

BinaryTreePathsSolution solution = new BinaryTreePathsSolution();
List<String> res = solution.binaryTreePaths(root);

for (int i = 0;i < res.size();i++){
System.out.print(res.get(i) + " ");
}
System.exit(0);
}

}


输出:

0->1->3 0->1->4->7 0->2->5 0->2->6
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: