LeetCode(257):二叉树的所有路径
题目描述
目前处理二叉树的问题,多在进行二叉树的深度优先遍历和广度优先遍历。看到这个题目的第一瞬间,想到的就是深度优先遍历。从根节点走到叶子节点。
题解
深度优先遍历(递归实现)
/**
* 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> result = new LinkedList<>();
if(root == null){
return result;
}
path(root,root.val+"",result);
return result;
}
public static void path(TreeNode root,String s,List<String> result){
if(root.left == null && root.right == null){
result.add(s);
return;
}
if(root.left != null){
path(root.left,s+"->"+root.left.val,result);
}
if(root.right != null){
path(root.right,s+"->"+root.right.val,result);
}
}
}
广度优先遍历(队列)
/**
* 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) {
// 广度优先遍历,使用队列。设计一个Tree,其中一项保存path
List<String> result = new LinkedList<>();
if(root == null){
return result;
}
Queue<Tree> queue = new LinkedList<>();
Tree tree = new Tree(root,root.val+"");
queue.offer(tree);
while(!queue.isEmpty()){
tree = queue.poll();
if(tree.treeNode.left == null && tree.treeNode.right == null){
result.add(tree.path);
}
if(tree.treeNode.right != null){
queue.offer(new Tree(tree.treeNode.right,tree.path+"->"+tree.treeNode.right.val));
}
if(tree.treeNode.left != null){
queue.offer(new Tree(tree.treeNode.left,tree.path+"->"+tree.treeNode.left.val));
}
}
return result;
}
}
class Tree{
TreeNode treeNode;
String path;
Tree(TreeNode treeNode,String path) {
this.treeNode = treeNode;
this.path = path;
}
}