题目描述:
给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [1,2,3,null,5] 输出:[“1->2->5”,“1->3”] 示例 2:
输入:root = [1] 输出:[“1”]
迭代法:
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
if (root == null)
return result;
Stack<Object> stack = new Stack<>();
// 节点和路径同时入栈
stack.push(root);
stack.push(root.val + "");
while (!stack.isEmpty()) {
// 节点和路径同时出栈
String path = (String) stack.pop();
TreeNode node = (TreeNode) stack.pop();
// 若找到叶子节点
if (node.left == null && node.right == null) {
result.add(path);
}
//右子节点不为空
if (node.right != null) {
stack.push(node.right);
stack.push(path + "->" + node.right.val);
}
//左子节点不为空
if (node.left != null) {
stack.push(node.left);
stack.push(path + "->" + node.left.val);
}
}
return result;
}
}
递归法:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public void getPath(TreeNode cur,List<Integer> path,List<String> result)
{
path.add(cur.val);
if (cur.left == null && cur.right == null) {
// 输出
StringBuilder sb = new StringBuilder();
for (int i = 0; i < path.size() - 1; i++) {
sb.append(path.get(i)).append("->");
}
sb.append(path.get(path.size() - 1));
result.add(sb.toString());
return;
}
if(cur.left!=null)
{
getPath(cur.left,path,result);
path.remove(path.size()-1);
}
if(cur.right!=null)
{
getPath(cur.right,path,result);
path.remove(path.size()-1);
}
}
public List<String> binaryTreePaths(TreeNode root) {
List<String> ans=new ArrayList<String>();
if(root==null)
{
return ans;
}
List<Integer> path=new ArrayList<>();
getPath(root,path,ans);
return ans;
}
}