思路:
逐层访问,通过访问当前层来得到下一层的节点。结束标志是下一层没有节点。
Go
package main import . "nc_tools" /* * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } *//** * * @param root TreeNode类 * @return int整型二维数组 */ func levelOrder( root *TreeNode ) [][]int { // write code here result := make([][]int,0) if root == nil{ return result } curSet := make([]*TreeNode,0) curSet = append(curSet,root) tmpResult := make([]int,0) for _,node := range curSet{ tmpResult = append(tmpResult,node.Val) } result = append(result,tmpResult)
for len(curSet) > 0 { next := make([]*TreeNode,0) tmpResult = make([]int,0) for _,node := range curSet{ if node.Left != nil{ next = append(next,node.Left) tmpResult = append(tmpResult,node.Left.Val) } if node.Right != nil{ next = append(next,node.Right) tmpResult = append(tmpResult,node.Right.Val) } } if len(tmpResult) > 0{ result = append(result,tmpResult) } curSet = next }
return result
} 运行时间 8ms 占用内存 1168KB
C++
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */#include <iterator> class Solution { public: /** * * @param root TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int> > levelOrder(TreeNode* root) { // write code here vector<vector<int>> res; if(root == nullptr){ return res; } vector<TreeNode*> curLevel; curLevel.push_back(root);
vector<int> tmpResult; tmpResult.push_back(root->val); res.push_back(tmpResult);
while(curLevel.size() > 0){ tmpResult = vector<int>(); vector<TreeNode*> nextLevel;
for(auto &ele: curLevel){ if(ele->left != nullptr){ tmpResult.push_back(ele->left->val); nextLevel.push_back(ele->left); } if(ele->right != nullptr){ tmpResult.push_back(ele->right->val); nextLevel.push_back(ele->right); } } if(tmpResult.size() > 0){ res.push_back(tmpResult); } curLevel = nextLevel; } return res; } }; 运行时间 5ms 占用内存 516KB https://clang.llvm.org/extra/clang-tidy/checks/modernize/loop-convert.html 标签:node,层序,TreeNode,BM26,back,tmpResult,二叉树,root,append From: https://www.cnblogs.com/starter-songudi/p/17089406.html