二叉树的层次遍历

来源:互联网 发布:马丁全单吉他知乎 编辑:程序博客网 时间:2024/05/24 03:37

问题描述:

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

样例:

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

  3 / \9  20  /  \ 15   7

返回他的分层遍历结果:

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

解题思路:

用两个队列交替使用存储,将根节点放在队列0里,然后用循环取出来将孩子放在另个队列,接着第二次循环在访问另一个队列,做相同的操作。

代码:

/** * 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> >tree;    vector<vector<int>> levelOrder(TreeNode *root) {        // write your code here        TreeNode *q;        if (root== NULL) return tree;        queue<TreeNode *> tem[2];        tem[0].push(root);        int i= 0;        while (!tem[0].empty() || !tem[1].empty()) {            vector<int> a;            while (!tem[i].empty()) {                a.push_back(tem[i].front()->val);                if (tem[i].front()->left!= NULL) tem[(i+1)%2].push(tem[i].front()->left);                if (tem[i].front()->right!= NULL) tem[(i+1)%2].push(tem[i].front()->right);                tem[i].pop();            }            tree.push_back(a);            i=(i+1)%2;        }        return tree;    }};


感想:

借鉴的思路,感觉在逻辑上是很好的在思路。


0 0
原创粉丝点击