[Leetcode] Binary tree level order traversal二叉樹層次遍歷


Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree{3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

 

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

 

confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
 
二叉樹的層次遍歷一般是利用隊列結構,先將root入隊,然后在隊列變空之前反復的迭代。迭代部分:首先是取出隊首節點並訪問,左孩子入隊,然后右孩子入隊。
方法一:@ 牛客網NBingGee
因為這題是以每層的形式輸出,不是整體。所以需要一個中間變量levelNode來存放每層的節點,關鍵在於如何層與層之間的節點分開。可以用兩個計數器,一個存放當前層的節點個數(levCount),一個存放下一層的節點個數(count)。如果levCount==0,則將當前層的節點存入res中,更新levCount並進入下一行。過程中,二叉樹層次遍歷的整體思想不變,只不過在循環體的最后加了一段判斷是否存入res的代碼。
/**
 * 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<vector<int> > levelOrder(TreeNode *root) 
    {
        vector<vector<int>> res;
        vector<int> levelNode;
        queue<TreeNode *> Q;
        if(root) Q.push(root);
        int count=0;         //下一層元素的個數
        int levCount=1;   //當前層元素個數,初始為第一層
        while( !Q.empty())
        {
            TreeNode *cur=Q.front();
            levelNode.push_back(cur->val);
            Q.pop();
            levCount--;
            if(cur->left)
            {
                Q.push(cur->left);
                count++;
            }
            if(cur->right)
            {
                Q.push(cur->right);
                count++;
            }
            if(levCount==0)
            {
                res.push_back(levelNode);
                levCount=count;
                count=0;
                levelNode.clear();  //清空levelNode,為下層
            }
        }
        return res;
    }
};

 

方法二:

 思路:遍歷完一層以后,隊列中節點的個數就是二叉樹下一層的節點數。實時更新隊列中節點的個數,每層的遍歷。

/**
 * 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<vector<int> > levelOrder(TreeNode *root) 
    {
        vector<vector<int>> res;
        queue<TreeNode *> Q;
        if(root)    Q.push(root);

        while( !Q.empty())
        {
            int count=0;
            int levCount=Q.size();
            vector<int> levNode;
            
            //遍歷當前層
            while(count<levCount)
            {
                TreeNode *curNode=Q.front();
                Q.pop();
                levNode.push_back(curNode->val);
                if(curNode->left)
                    Q.push(curNode->left);
                if(curNode->right)
                    Q.push(curNode->right);
                count++;
            }
            res.push_back(levNode);
        }
        return res;    
    }
};

 

 方法三:
利用隊列,在每一層結束時向棧中壓入NULL, 則遇到NULL就標志一層的結束,就可以存節點了。
/**
 * 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<vector<int> > levelOrder(TreeNode *root) 
    {
        vector<vector<int>> res;
        queue<TreeNode *> Q;
        if(!root)    return res;    
        Q.push(root);
        Q.push(NULL);
        vector<int> levNode;       //存放每層的結點的值
     
        while( !Q.empty())
        {
            TreeNode *cur=Q.front();
            Q.pop();
            if(cur)
            {
                levNode.push_back(cur->val);
                if(cur->left)   
                    Q.push(cur->left);
                if(cur->right)
                    Q.push(cur->right);
            }
            else
            {
                res.push_back(levNode);
                levNode.clear();
                if( !Q.empty())
                    Q.push(NULL);
            }
        }
        return res;    
    }
};

 

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM