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:
All root-to-leaf paths are:
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;
}
}
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;
}
}
相关文章推荐
- Leetcode 257 Binary Tree Paths 二叉树 DFS
- LeetCode@DFS_257_Binary_Tree_Paths
- LeetCode 257 Binary Tree Paths (DFS)
- leetcode Binary Tree Paths 257
- LeetCode 257 Binary Tree Paths
- 【LeetCode】257 - Binary Tree Paths
- Java [Leetcode 257]Binary Tree Paths
- leetcode——257——Binary Tree Paths
- LeetCode题解-257-Binary Tree Paths
- [leetcode-257]Binary Tree Paths(java)
- LeetCode257:Binary Tree Paths
- Leetcode 257 Binary Tree Paths
- LeetCode 257:Binary Tree Paths
- LeetCode 257: Binary Tree Paths
- leetcode257 Binary Tree Paths
- Leetcode 257 -- Binary Tree Paths
- Leetcode_257_Binary Tree Paths
- LeetCode257——Binary Tree Paths
- leetcode_c++:树:Binary Tree Paths(257)
- Leetcode_257_Binary Tree Paths