LeetCode 102.Binary Tree Level Order Traversal (二叉樹的層次遍歷)
阿新 • • 發佈:2018-12-12
題目描述:
給定一個二叉樹,返回其按層次遍歷的節點值。 (即逐層地,從左到右訪問所有節點)。
例如:
給定二叉樹: [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回其層次遍歷結果:
[ [3], [9,20], [15,7] ]
AC C++ Solution:
遞迴:
/** * 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) { buildvector(root,0); return res; } void buildvector(TreeNode *root, int depth) { if(root == NULL) return; if(res.size() == depth) res.push_back(vector<int>()); res[depth].push_back(root->val); buildvector(root->left, depth+1); buildvector(root->right,depth+1); } private: vector< vector<int> > res; };
佇列:
/** * 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; if(!root) return res; queue<TreeNode*> q; q.push(root); q.push(NULL); vector<int> cur_vec; while(!q.empty()) { TreeNode *t = q.front(); q.pop(); if(t == NULL) { res.push_back(cur_vec); cur_vec.resize(0); if(q.size() > 0) q.push(NULL); //每層之間用一個NULL作為分隔符 } else { //把每個節點的值存入cur_vec,並把下一層的節點加入佇列 cur_vec.push_back(t->val); if(t->left) q.push(t->left); if(t->right) q.push(t->right); } } return res; } };