[leetcode]257.Binary Tree Paths
题目
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/
2 3
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
解法一
思路
用数的DFS(深度优先遍历包括先序,中序,后序遍历)。用两个栈,其中一个栈来保存结点,另外一个栈来保存从根节点到当前结点的路径。两个栈一直是同步的,也就是说每次出栈的结点与字符串是对应关系。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<>();
Stack<TreeNode> nStack = new Stack<>();
Stack<String> sStack = new Stack<>();
if(root == null) return list;
nStack.push(root);
sStack.push("");
while(!nStack.isEmpty()){
TreeNode curNode = nStack.pop();
String curString = sStack.pop();
if(curNode.left == null && curNode.right == null)
list.add(curString + curNode.val);
if(curNode.right != null) {
nStack.push(curNode.right);
sStack.push(curString + curNode.val + "->");
}
if(curNode.left != null) {
nStack.push(curNode.left);
sStack.push(curString + curNode.val + "->");
}
}
return list;
}
}
解法二
思路
用树的BFS(实际就是层次遍历)。和解法一一样,把栈改成队列即可。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<>();
Queue<TreeNode> nQueue = new LinkedList<>();
Queue<String> sQueue = new LinkedList<>();
if(root == null) return list;
nQueue.add(root);
sQueue.add("");
while(!nQueue.isEmpty()){
TreeNode curNode = nQueue.remove();
String curString = sQueue.remove();
if(curNode.left == null && curNode.right == null)
list.add(curString + curNode.val);
if(curNode.right != null) {
nQueue.add(curNode.right);
sQueue.add(curString + curNode.val + "->");
}
if(curNode.left != null) {
nQueue.add(curNode.left);
sQueue.add(curString + curNode.val + "->");
}
}
return list;
}
}
解法三
思路
用递归,其实也是DFS的思想
代码
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> answer = new ArrayList<String>();
if (root != null) searchBT(root, "", answer);
return answer;
}
private void searchBT(TreeNode root, String 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);
}
}