leecode每日一題01- Binary Tree Level Order Traversal [Medium]
阿新 • • 發佈:2019-01-05
關於二叉樹的遍歷查詢。
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
/** * 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 = new vector<vector<int>>(); levelHelper(res,root,0); return *res; } //採用DFS的方法求解 void levelHelper(vector<vector<int>>* res,TreeNode* root,int level) { if(root == NULL) return; if(level >= res->size()) { res->push_back(vector<int>()); } // cout<<"root_val="<<root->val<<" level="<<level<<endl; res->at(level).push_back(root->val); levelHelper(res,root->left,level+1); levelHelper(res,root->right,level+1); } };
PS:本文摘自網路資源,僅供個人學習記錄參考使用,同時與大家分享。