我的方法。每个队列保存一层的node:
/** * 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>> res; queue<TreeNode*> qu; if(!root){ return res; } qu.push(root); soln(res,qu); return res; } void soln(vector<vector<int>>& res, queue<TreeNode*>& qu1){ if(qu1.empty()){ return; } queue<TreeNode*> qu2; vector<int> tem; while(!qu1.empty()){ tem.push_back(qu1.front()->val); if(qu1.front()->left){ qu2.push(qu1.front()->left); } if(qu1.front()->right){ qu2.push(qu1.front()->right); } qu1.pop(); } res.push_back(tem); soln(res,qu2); } };
队列
可以用递归。
为什么非得一层加完了再加下一层呢?没有必要。
class Solution { private: vector<vector<int>>res; public: void levelOrder(struct TreeNode* root,int level){ if(root==NULL)return ; if(level==res.size()){ vector<int> v; res.push_back(v); } res[level].push_back(root->val); levelOrder(root->left,level+1); levelOrder(root->right,level+1); } vector<vector<int>> levelOrder(TreeNode* root) { levelOrder(root,0); return res; } };
递归
原文地址:https://www.cnblogs.com/azureice/p/leetcode102.html
时间: 2024-11-02 17:54:40