java 容器、二叉树操作、107
二叉樹(shù)本身固有的遞歸性質(zhì),通常可以用遞歸算法解決,雖然遞歸代碼簡(jiǎn)介,但是性能不如非遞歸算法。
常用的操作是構(gòu)建二叉樹(shù)、遍歷二叉樹(shù)(先序、中序、后序、都屬于DFS深度優(yōu)先搜索算法,使用棧來(lái)實(shí)現(xiàn)),廣度優(yōu)先BFS使用隊(duì)列來(lái)遍歷。
參考博客:
鏈表、二叉樹(shù)操作、深度優(yōu)先、廣度優(yōu)先的算法
注意:
?
這個(gè)圖里面虛點(diǎn)框代表的是接口,虛線(xiàn)框代表的是抽象類(lèi),實(shí)線(xiàn)框代表的實(shí)現(xiàn)了接口或者繼承了抽象類(lèi)的類(lèi),加粗的實(shí)線(xiàn)框代表的是常用類(lèi):HashMap、HashSet、ArrayList、LinkedList,這張圖沒(méi)有給出Queue的實(shí)現(xiàn),
?
可以看到LinkedList是Deque的實(shí)現(xiàn)類(lèi),所以to sum up,各種棧、隊(duì)列的接口實(shí)現(xiàn)都可以找LinkedList,只是不同的接口都有不同的方法。
?
下面看leetcode的題目:
【107】Binary Tree Level Order Traversal II
Given a binary tree, return the?bottom-up level order?traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree?{3,9,20,#,#,15,7},
?
return its bottom-up level order traversal as:
[[15,7],[9,20],[3] ]思路:其實(shí)是層序遍歷二叉樹(shù),編程之美上有這個(gè),其實(shí)也就是 BFS,如果使用隊(duì)列來(lái)實(shí)現(xiàn)的話(huà),會(huì)超時(shí),編程之美上用的vector,所以用一般的動(dòng)態(tài)數(shù)組就可以了。 /*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*///It's an iterative way by two "while circles" to travesal every level of the tree, BFS actually, u can use queue to do it ,but it seems time will exceed public class Solution {public List<List<Integer>> levelOrderBottom(TreeNode root) {List<List<Integer>> nodeData = new ArrayList<List<Integer>>();if(root==null)return nodeData;List<TreeNode> nodeList = new ArrayList<TreeNode>();nodeList.add(root);int start = 0;int last = 1; //value 1 is for the 0 levelwhile(start<nodeList.size()){last = nodeList.size();//update the last value of the new levelList<Integer> tempList = new ArrayList<Integer>(); //store the node data in every levelwhile(start < last){TreeNode tempNode = (TreeNode)nodeList.get(start);if(tempNode!=null)tempList.add(tempNode.val);if(tempNode.left!=null)nodeList.add(tempNode.left);if(tempNode.right!=null)nodeList.add(tempNode.right);start++;} nodeData.add(0,tempList);}return nodeData;} }
?
轉(zhuǎn)載于:https://www.cnblogs.com/lucky-star-star/p/5043804.html
總結(jié)
以上是生活随笔為你收集整理的java 容器、二叉树操作、107的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: redis复习
- 下一篇: 关于tar无法解压缩问题