美文网首页
leetcode--102--二叉树的层序遍历

leetcode--102--二叉树的层序遍历

作者: minningl | 来源:发表于2020-05-30 17:10 被阅读0次

题目:
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。

示例:
二叉树:[3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

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

链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal

思路:
1、采用BFS对每一层进行遍历,并且分别保存每一层的结果

Python代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        ret = []
        curr = [root]
        if not root:
            return ret

        while len(curr)>0:
            temp = []
            line = []
            for item in curr:
                line.append(item.val)
                if item.left:
                    temp.append(item.left)
                if item.right:
                    temp.append(item.right)
            ret.append(line)
            curr, temp = temp, curr

        return ret

C++代码:

/**
 * 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>>  ret;
        if (root == nullptr) return {};
        
        vector<TreeNode*> curr = {root};

        while (curr.size()>0){
            vector<TreeNode*> temp;
            vector<int> line;
            for (auto item : curr){
                line.push_back(item->val);
                if(item->left) temp.push_back(item->left);
                if(item->right) temp.push_back(item->right);
            }
            curr.swap(temp);
            ret.push_back(line);
        }
        return ret;

    }
};

相关文章

网友评论

      本文标题:leetcode--102--二叉树的层序遍历

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