rocksc30 / LeetCode

用于力扣刷题打卡
2 stars 0 forks source link

102. 二叉树的层序遍历 #34

Open Ni-Guvara opened 1 year ago

Ni-Guvara commented 1 year ago
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        if(nullptr == root)
            return {};

        vector<vector<int>> ret;
        queue<TreeNode *> auxq1;
        queue<TreeNode *> auxq2;

        auxq1.push(root);

        while(!auxq1.empty() || !auxq2.empty()){

            vector<int>num;
            while(!auxq1.empty())
            {
                TreeNode * node = auxq1.front();
                if(node)
                    num.push_back(node->val);

                auxq1.pop();
                if(node)
                {
                    if(node->left)
                        auxq2.push(node->left);
                    if(node->right)
                        auxq2.push(node->right);
                }
            }
            ret.push_back(num);
            auxq1.swap(auxq2);

        }

        return ret;

    }
};
rocksc30 commented 1 year ago
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {

    public List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> ans = new ArrayList<>();
        if(root == null){
            return ans;
        }
        LinkedList<TreeNode> que = new LinkedList<>();
        que.addFirst(root);
        while(!que.isEmpty()){
            List<Integer> row = new ArrayList<>();
            int size = que.size();
            for(int i = 0; i < size; i++){
                TreeNode cur = que.pollFirst();
                row.add(cur.val);
                if(cur.left != null){
                    que.addLast(cur.left);
                }
                if(cur.right != null){
                    que.addLast(cur.right);
                }
            }
            ans.add(row);
        }
        return ans;
    }
}