二叉树层次遍历

给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)

样例

给一棵二叉树 {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) {
        // write your code here
        queue<TreeNode* > q;
        vector<vector<int > > result;
        if(root == NULL)return result;
        q.push(root);
        int count1 = 1,count2 = 0;
        vector<int > sur;
        while(!q.empty() )
        {
            
            TreeNode *tmp = q.front();
            q.pop();
            sur.push_back(tmp->val);
            count1--;
            if(tmp->left != NULL)
            {
                q.push(tmp->left);
                count2++;
            }
            if(tmp->right != NULL)
            {
                q.push(tmp->right);
                count2++;
            }
            if(count1 == 0)
            {
                count1 = count2;
                count2 = 0;
                result.push_back(sur);
                sur.clear();
            }
        }
        return result;
    }
};

count1保存当前层次的节点数,count2保存下一层的节点数,每出队列一个节点当前层节点数减一直到为零,count1与count2互换,并将vector保存下来。

posted @ 2017-06-12 16:53  mximo  阅读(176)  评论(0编辑  收藏  举报