leetcode刷题篇 102题二叉树的层序遍历 java C++版本

先看题目:
在这里插入图片描述
思路分析:
两种思路,
第一种是利用二叉树的层序遍历的方法,DFS,
第一种是利用二叉树的深度遍历,DFS,通过记录二叉树的深度来区分是第几层,利用二叉树的前序遍历可以满足要求

直接看代码
C++版,BFS

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        return BFS(root);
    }
private:
    vector<vector<int>> BFS(TreeNode* root) {
        if (!root) return {};
        vector<vector<int>> ans;
        vector<TreeNode*> curr, next;
        curr.push_back(root);
        while(!curr.empty()) {
            ans.push_back({});
            for (TreeNode* node : curr) {
                ans.back().push_back(node->val);
                if(node->left) next.push_back(node->left);
                if(node->right) next.push_back(node->right);
            }
            curr.swap(next);
            next.clear();
        }
        return ans;
    }
};

在这里插入图片描述
C++版:DFS:

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        DFS(root, 0, ans);
        return ans;
    }
private:
    void DFS(TreeNode* root, int depth, vector<vector<int>>& ans) {
        if(!root) return;
        while(ans.size() <= depth) {
            ans.push_back({});
        }
        ans[depth].push_back(root->val);
        DFS(root->left, depth + 1, ans);
        DFS(root->right, depth + 1, ans);
    }
};

java版:BFS:

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()) {
            List<Integer> leverRes = new ArrayList<>();
            Queue<TreeNode> tmpNode = new LinkedList<>();
            while(!queue.isEmpty()) {
                TreeNode currentNode = queue.remove();
                leverRes.add(currentNode.val);
                if (currentNode.left != null) tmpNode.add(currentNode.left);
                if (currentNode.right != null) tmpNode.add(currentNode.right);
            }
            result.add(leverRes);
            queue = tmpNode;
        }
        return result;
    }
}

ok,今天先到这里吧~

猜你喜欢

转载自blog.csdn.net/weixin_45806131/article/details/108434204
今日推荐