java 容器、二叉树操作、107
二叉樹本身固有的遞歸性質,通常可以用遞歸算法解決,雖然遞歸代碼簡介,但是性能不如非遞歸算法。
常用的操作是構建二叉樹、遍歷二叉樹(先序、中序、后序、都屬于DFS深度優先搜索算法,使用棧來實現),廣度優先BFS使用隊列來遍歷。
參考博客:
鏈表、二叉樹操作、深度優先、廣度優先的算法
注意:
?
這個圖里面虛點框代表的是接口,虛線框代表的是抽象類,實線框代表的實現了接口或者繼承了抽象類的類,加粗的實線框代表的是常用類:HashMap、HashSet、ArrayList、LinkedList,這張圖沒有給出Queue的實現,
?
可以看到LinkedList是Deque的實現類,所以to sum up,各種棧、隊列的接口實現都可以找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] ]思路:其實是層序遍歷二叉樹,編程之美上有這個,其實也就是 BFS,如果使用隊列來實現的話,會超時,編程之美上用的vector,所以用一般的動態數組就可以了。 /*** 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;} }
?
轉載于:https://www.cnblogs.com/lucky-star-star/p/5043804.html
總結
以上是生活随笔為你收集整理的java 容器、二叉树操作、107的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: redis复习
- 下一篇: 关于tar无法解压缩问题