二叉樹的層次遍歷

問題描述:

給出一棵二叉樹,返回其節點值的層次遍歷(逐層從左往右訪問)

樣例

給一棵二叉樹 {3,9,20,#,#,15,7} :

  3
 / \
9  20
  /  \
 15   7

返回他的分層遍歷結果:

[
  [3],
  [9,20],
  [15,7]
]
解題思路:

用隊列先進先出的特點,將每層的節點入對,後依次出隊,然後將出隊節點的下一層保存,並將出隊節點存入向量中,層層進行,直到最後一層。

代碼:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Level order a list of lists of integer
     */
public:
    vector<vector<int>> levelOrder(TreeNode *root) {
            vector<vector<int>> result;  
        queue<TreeNode*>q;        //      
        vector<int> level;       //每層結果  
        int size,i;  
        TreeNode* p;  
          
        if(root==NULL) return result;  
        q.push(root);            //入隊  
        while(!q.empty()) {  //隊列中有幾個元素就依次遍歷每個元素的左右結點  
            level.clear();  
            size=q.size();  
            for(i=0; i<size; i++) {  
                p=q.front();     //隊首元素值賦給p  
                q.pop();         //出隊  
                level.push_back(p->val);  
                if(p->left) {    //依次壓入左右結點元素  
                    q.push(p->left);  
                }  
                if(p->right) {  
                    q.push(p->right);  
                }  
            }  
            result.push_back(level);   //添加每層數據  
        }  
        return result;  
        // write your code here
    }
};

感想:

注意運用隊列特性的方法

發佈了49 篇原創文章 · 獲贊 0 · 訪問量 5004
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章