[Leetcode][第257题][JAVA][二叉树的所有路径][BFS][DFS]
生活随笔
收集整理的這篇文章主要介紹了
[Leetcode][第257题][JAVA][二叉树的所有路径][BFS][DFS]
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
【問(wèn)題描述】[簡(jiǎn)單]
【解答思路】
1. DFS
時(shí)間復(fù)雜度:O(N^2) 空間復(fù)雜度:O(N^2)
時(shí)間復(fù)雜度更高 ,使用String+“ ”拼接字符串
class Solution {//這行代碼可不敢寫(xiě)這里,leetcode提交會(huì)出問(wèn)題的。。。。!!!//private static List<String> res = new ArrayList<String>();public List<String> binaryTreePaths(TreeNode root) {List<String> res = new ArrayList<String>();if(root == null)return res;BL(root,res,"");return res;}public static void BL(TreeNode node,List<String> res,String str){if(node.left != null) BL(node.left, res, str + node.val + "->");if(node.right != null) BL(node.right, res, str + node.val + "->");if(node.left == null && node.right == null) res.add(str + node.val);} }鏈接:https://leetcode-cn.com/problems/binary-tree-paths/solution/chang-gui-cao-zuo-50di-gui-by-gu-xiong-007/2. BFS
時(shí)間復(fù)雜度:O(N2) 空間復(fù)雜度:O(N2)
【總結(jié)】
1. String StringBuffer StringBuilder
2.二叉樹(shù)遍歷
- 前序遍歷 先輸出當(dāng)前結(jié)點(diǎn)的數(shù)據(jù),再依次遍歷輸出左結(jié)點(diǎn)和右結(jié)點(diǎn)
- 中序遍歷 先遍歷輸出左結(jié)點(diǎn),再輸出當(dāng)前結(jié)點(diǎn)的數(shù)據(jù),再遍歷輸出右結(jié)點(diǎn)
- 后續(xù)遍歷 先遍歷輸出左結(jié)點(diǎn),再遍歷輸出右結(jié)點(diǎn),最后輸出當(dāng)前結(jié)點(diǎn)的數(shù)據(jù)
3.復(fù)制粘貼時(shí)候要小心 修改相應(yīng)代碼 腦子模擬代碼 快速排查錯(cuò)誤 多從自己寫(xiě)的代碼 切忌浮躁
轉(zhuǎn)載鏈接:https://leetcode-cn.com/problems/binary-tree-paths/solution/er-cha-shu-de-suo-you-lu-jing-by-leetcode-solution/
參考鏈接:https://leetcode-cn.com/problems/binary-tree-paths/solution/chang-gui-cao-zuo-50di-gui-by-gu-xiong-007/
總結(jié)
以上是生活随笔為你收集整理的[Leetcode][第257题][JAVA][二叉树的所有路径][BFS][DFS]的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: jenkins 部署文档
- 下一篇: 带你如何使用npm下载包