二叉树的层次遍历

来源:互联网 发布:linux route -p 编辑:程序博客网 时间:2024/05/29 19:31

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

样例

给一棵二叉树 {3,9,20,#,#,15,7} :

  3 / \9  20  /  \ 15   7

返回他的分层遍历结果:

[  [3],  [9,20],  [15,7]]
解题思路:建立一个队列,循环时在每一行后面加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
        vector<vector<int> > cengci;
        queue<TreeNode*> q;
        q.push(root);
        q.push(NULL);
        vector<int> it;
        while(q.size()!=0)
        {
            TreeNode *p = q.front();
            q.pop();
            if(p!=NULL)
           {
               it.push_back(p->val);
               if(p->left!=NULL) 
               q.push(p->left);
               if(p->right!=NULL)
               q.push(p->right);
           }
           else
           {
               if(it.size()!=0)
               {
                  cengci.push_back(it);
                  it.clear();
                  q.push(NULL);
               }
           }
        }
       return cengci;
    }
};

个人感想:在第一个根节点后也要加NULL。

0 0
原创粉丝点击