日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

java 容器、二叉树操作、107

發(fā)布時(shí)間:2025/3/17 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java 容器、二叉树操作、107 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

二叉樹(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},

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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。