您的位置:首页 > 其它

LeetCode@DFS_257_Binary_Tree_Paths

2017-06-20 11:43 369 查看
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"]


java:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution
{

public List<String> binaryTreePaths(TreeNode root)
{
List<String> path = new LinkedList<>();
Stack<TreeNode> node = new Stack<>();
Stack<String> subPath = new Stack<>();

if(root == null)
{
return path;
}
node.push(root);
subPath.push("");
while (!node.isEmpty())
{
TreeNode currNode = node.pop();
String curr = subPath.pop();
//stack.pop();
if (currNode.left != null)
{
subPath.push(curr+currNode.val+"->");
node.push(currNode.left);
}
if (currNode.right != null)
{
subPath.push(curr+currNode.val+"->");
node.push(currNode.right);
}
if (currNode.left == null && currNode.right == null)
{
path.add(curr+currNode.val);
}
}
return path;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: