如何进行python中二叉树的级别顺序遍历分析

今天就跟大家聊聊有关如何进行python中二叉树的级别顺序遍历分析,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

二叉树级顺序遍历

给定二叉树,返回其节点值的级别顺序遍历。(即,从左到右,逐级)。

例如:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

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

解题思路:

采用双队列来处理。

用当前队列current来处理本层的所有节点,将本层信息记录在vector中。用next来记录下一层的节点信息。

当前队列处理后,将本层信息的vector存储到结果vector中。清空存储本层信息的vector。将current和next交换。然后重新处理current队列。

代码如下:

/**
 * Definition for a binary tree node.
 * 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>> result;
        queue<TreeNode *> current,next;
        vector<int> level;
        
        if(NULL == root)
            return result;
        current.push(root);
        
        while(current.size() > 0)
        {
            while(current.size() > 0)
            {
                TreeNode *p = current.front();
                current.pop();
                level.push_back(p->val);
                if(p->left)
                    next.push(p->left);
                if(p->right)
                    next.push(p->right);
            }
            result.push_back(level);
            level.clear();
            current.swap(next);
        }
        
        return result;
    }
};

看完上述内容,你们对如何进行python中二叉树的级别顺序遍历分析有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。