本篇文章為大家展示了如何解析python二叉樹的右視圖,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于網(wǎng)站設(shè)計制作、成都網(wǎng)站設(shè)計、達(dá)茂旗網(wǎng)絡(luò)推廣、小程序開發(fā)、達(dá)茂旗網(wǎng)絡(luò)營銷、達(dá)茂旗企業(yè)策劃、達(dá)茂旗品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們最大的嘉獎;創(chuàng)新互聯(lián)為所有大學(xué)生創(chuàng)業(yè)者提供達(dá)茂旗建站搭建服務(wù),24小時服務(wù)熱線:18980820575,官方網(wǎng)址:chinadenli.net
給定一棵二叉樹,想象自己站在它的右側(cè),按照從頂部到底部的順序,返回從右側(cè)所能看到的節(jié)點值。
示例:
輸入: [1,2,3,null,5,null,4] 輸出: [1, 3, 4] 解釋: 1 <--- / \ 2 3 <--- \ \ 5 4 <---
答案:
1public List<Integer> rightSideView(TreeNode root) {
2 if (root == null)
3 return new ArrayList();
4 Queue<TreeNode> queue = new LinkedList();
5 queue.offer(root);
6 List<Integer> res = new ArrayList();
7 while (!queue.isEmpty()) {
8 int size = queue.size();
9 while (size-- > 0) {
10 TreeNode cur = queue.poll();
11 if (size == 0)
12 res.add(cur.val);
13 if (cur.left != null)
14 queue.offer(cur.left);
15 if (cur.right != null)
16 queue.offer(cur.right);
17 }
18 }
19 return res;
20}
解析:
原理很簡單,我們通過bfs(廣度優(yōu)先搜索)遍歷每一行,然后記錄一下每一行的最右的那個節(jié)點即可。在看一種遞歸的解法
1public List<Integer> rightSideView(TreeNode root) {
2 List<Integer> result = new ArrayList<Integer>();
3 rightView(root, result, 0);
4 return result;
5}
6
7public void rightView(TreeNode curr, List<Integer> result, int currDepth) {
8 if (curr == null) {
9 return;
10 }
11 if (currDepth == result.size()) {
12 result.add(curr.val);
13 }
14 rightView(curr.right, result, currDepth + 1);
15 rightView(curr.left, result, currDepth + 1);
16}
通過dfs(深度優(yōu)先搜索)遍歷每一個節(jié)點,他先遍歷的是右節(jié)點,然后是左節(jié)點,當(dāng)遍歷的深度等于result的長度的時候,把當(dāng)前節(jié)點加入到result中。
上述內(nèi)容就是如何解析python二叉樹的右視圖,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
網(wǎng)站欄目:如何解析python二叉樹的右視圖
網(wǎng)站鏈接:http://chinadenli.net/article22/gsjgcc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)網(wǎng)站建設(shè)、網(wǎng)站設(shè)計公司、域名注冊、建站公司、用戶體驗、動態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)