Leetcode:107.二叉樹的層次遍歷
阿新 • • 發佈:2018-11-13
給定一個二叉樹,返回其節點值自底向上的層次遍歷。 (即按從葉子節點所在層到根節點所在的層,逐層從左向右遍歷)
例如:
給定二叉樹 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回其自底向上的層次遍歷為:
[ [15,7], [9,20], [3] ]
解題思路:
二叉樹的層次遍歷+反序輸出。層次遍歷請參考Leetcode:102.二叉樹的層次遍歷。
https://blog.csdn.net/qq_23523409/article/details/83720425
#define hasLChild(x) (!(x->left==NULL)) #define hasRChild(x) (!(x->right==NULL)) class Solution { public: vector<vector<int>> levelOrderBottom(TreeNode* root) { vector<vector<int>> res = levelOrder(root); for (int i = 1; i <= int(res.size())/2; i++) { swap(res[i - 1], res[int(res.size()) - i]); } return res; } vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> res; if (root == NULL) return res; queue<TreeNode*> Q; TreeNode* node; vector<int> res1; Q.push(root); while (!Q.empty()) { int size = Q.size(); res1.clear(); for (int i = 1; i <= size; i++) { node = Q.front(); res1.push_back(node->val); if (hasLChild(node)) { Q.push(node->left); } if (hasRChild(node)) { Q.push(node->right); } Q.pop(); } res.push_back(res1); } return res; } }; TreeNode* Int2Tree(vector<int> data) { TreeNode* root; int size = data.size(), pos = 1; if (size == 0) root = NULL; root = new TreeNode(data[0]); queue<TreeNode*> Q; TreeNode* temp; Q.push(root); while (pos < size) { if (!Q.empty()) { temp = Q.front(); if (data[pos] != NULL) { temp->left = new TreeNode(data[pos]); Q.push(temp->left); } if ((pos + 1 < size) && data[pos + 1] != NULL) { temp->right = new TreeNode(data[pos + 1]); Q.push(temp->right); } Q.pop(); } pos += 2; } return root; } |