leetcode:Binary Tree Right Side View,leetcodebinary

來源:互聯網
上載者:User

leetcode:Binary Tree Right Side View,leetcodebinary

一、 題目

  給你一個二叉樹,假設幾就站在樹的後邊,那麼此時你就只能看到最右邊的節點了。

例如:

    1            <---

  /   \

 2      3         <---

 \     \

  5     4          <---

返回值就是[1,3,4]

二、 分析

  對於樹的遍曆,我們通常會使用DFS或BFS,這個題目其實同樣是遍曆,不過呢,我們只記錄下來每一行最右邊的節點即可。我第一個思路是每次只訪問右節點,但仔細一想,並不一定所有的都是這種情況的,例如或許最右邊的節點在左半部分的。馬上否定了這個思路,想想不管怎樣都得是要遍曆所有節點的,不過我們是按照變相的前序走訪,即當前節點-右節點-左節點的順序,每次都將他們放進隊列,但是取的時候我們只記錄下第一個節點即可,其他的都釋放掉。


/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:        vector<int> rightSideView(TreeNode *root) {        vector<int> res;        if(root == NULL)            return res;        queue<TreeNode*> nQueue;        TreeNode *node = root;        nQueue.push(node);        while(!nQueue.empty()){            int size = nQueue.size();            for(int i = 0; i < size; i++){                node = nQueue.front();                nQueue.pop();                if(i == 0)                    res.push_back(node->val);                if(node->right)                    nQueue.push(node->right);                if(node->left)                    nQueue.push(node->left);            }        }        return res;    }};


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.