[LeetCode] #257 二叉樹的所有路徑
阿新 • • 發佈:2021-09-15
[LeetCode] #257 二叉樹的所有路徑
給你一個二叉樹的根節點 root
,按 任意順序 ,返回所有從根節點到葉子節點的路徑。
葉子節點 是指沒有子節點的節點。
輸入:root = [1,2,3,null,5]
輸出:["1->2->5","1->3"]
遞迴,將list作為引數傳遞
class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> list = new ArrayList<>(); if(root==null) returnlist; helper(root, "", list); return list; } public void helper(TreeNode root, String path, List<String> list){ if(root == null) return; if(root.left == null && root.right == null) list.add(path + root.val); else{ helper(root.left, path+root.val+"->", list); helper(root.right, path+root.val+"->", list); } } }
遞迴,將list作為全域性變數
class Solution { List<String> list = new ArrayList<>(); public List<String> binaryTreePaths(TreeNode root) { helper(root, ""); return list; }public void helper(TreeNode root, String path){ if(root == null) return; if(root.left == null && root.right == null) list.add(path + root.val); else{ helper(root.left, path+root.val+"->"); helper(root.right, path+root.val+"->"); } } }
遞迴,將list作為返回值
class Solution { public List<String> binaryTreePaths(TreeNode root) { return helper(root, ""); } public List helper(TreeNode root, String path){ List<String> list = new ArrayList<>(); if(root == null) return list; if(root.left == null && root.right == null) list.add(path + root.val); else{ list.addAll(helper(root.left, path+root.val+"->")); list.addAll(helper(root.right, path+root.val+"->")); } return list; } }
迭代
class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> paths = new ArrayList<String>(); if (root == null) return paths; Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>(); Queue<String> pathQueue = new LinkedList<String>(); nodeQueue.offer(root); pathQueue.offer(Integer.toString(root.val)); while (!nodeQueue.isEmpty()) { TreeNode node = nodeQueue.poll(); String path = pathQueue.poll(); if (node.left == null && node.right == null) { paths.add(path); } else { if (node.left != null) { nodeQueue.offer(node.left); pathQueue.offer(new StringBuffer(path).append("->").append(node.left.val).toString()); } if (node.right != null) { nodeQueue.offer(node.right); pathQueue.offer(new StringBuffer(path).append("->").append(node.right.val).toString()); } } } return paths; } }
知識點:無
總結:無