美文网首页二叉树之下
二叉树的层次遍历

二叉树的层次遍历

作者: 杰米 | 来源:发表于2016-09-05 11:24 被阅读903次

    给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
    样例
    给一棵二叉树 {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;
            if (root == NULL) {
                return  result;
            }
            // write your code here
           
            deque<TreeNode *>oneQueue;
            TreeNode *head = root;
            oneQueue.push_back(head);
            int currentLevel = 0;
            int currentLevelInternalCount = 1;
            int nextLevelInternalCount = 0;
            int count = 0;
            vector<int>levelNums;
            while(!oneQueue.empty()) {
                head = oneQueue.front();
                oneQueue.pop_front();
                count++;
               levelNums.push_back(head->val);
                if (head->left != NULL) {
                    oneQueue.push_back(head->left);
                    nextLevelInternalCount++;
                }
                if(head->right != NULL) {
                    oneQueue.push_back(head->right);
                    nextLevelInternalCount++;
                }
                 if (count == currentLevelInternalCount) {
                    vector<int> a = levelNums;
                    //vector<int>a(2,0);
                    result.push_back(a);
                    levelNums.clear();
                    count = 0;
                    currentLevelInternalCount = nextLevelInternalCount;
                    nextLevelInternalCount = 0;
                }
            }
            return result;
        }
    };
    
    

    相关文章

      网友评论

        本文标题:二叉树的层次遍历

        本文链接:https://www.haomeiwen.com/subject/oyjrettx.html