LeetCode@DFS_257_Binary_Tree_Paths

来源:互联网 发布:绘图纸用什么软件 编辑:程序博客网 时间:2024/06/07 18:06

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;} }




原创粉丝点击