[Leetcode][第257题][JAVA][二叉树的所有路径][BFS][DFS]
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                [Leetcode][第257题][JAVA][二叉树的所有路径][BFS][DFS]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                【問題描述】[簡單]
【解答思路】
1. DFS
時間復雜度:O(N^2) 空間復雜度:O(N^2)
 
時間復雜度更高 ,使用String+“ ”拼接字符串
class Solution {//這行代碼可不敢寫這里,leetcode提交會出問題的。。。。!!!//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
時間復雜度:O(N2) 空間復雜度:O(N2) 
 
【總結】
1. String StringBuffer StringBuilder
2.二叉樹遍歷
- 前序遍歷 先輸出當前結點的數據,再依次遍歷輸出左結點和右結點
- 中序遍歷 先遍歷輸出左結點,再輸出當前結點的數據,再遍歷輸出右結點
- 后續遍歷 先遍歷輸出左結點,再遍歷輸出右結點,最后輸出當前結點的數據
3.復制粘貼時候要小心 修改相應代碼 腦子模擬代碼 快速排查錯誤 多從自己寫的代碼 切忌浮躁
轉載鏈接: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/
總結
以上是生活随笔為你收集整理的[Leetcode][第257题][JAVA][二叉树的所有路径][BFS][DFS]的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: jenkins 部署文档
- 下一篇: 带你如何使用npm下载包
