本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Binary Tree Level Order Traversal
Total Accepted: 12292 Total
Submissions: 40417
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,#,#,15,7}
,
3 / 9 20 / 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
confused what "{1,#,2,3}"
means? >
read more on how binary tree is serialized on OJ.
题意:给定一棵二叉树,返回按层遍历的结果
思路1:bfs,定义一个新的struct,记录指针向节点的指针和每个节点所在的层
复杂度1:时间O(n),空间O(n)
思路2:dfs
递归函数:
void levelOrder(TreeNode *root, int level, vector<vector<int> >&result)
表示把根为root的树按层存放在result中,其中level表示当前的层数
复杂度2:时间O(n),空间O(n)
相关题目:
Binary Tree Level Order Traversal II
Binary Tree Zigzag Level Order Traversal
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: struct NodeWithLevel{ TreeNode *p; int level; NodeWithLevel(TreeNode *pp, int l):p(pp), level(l){} }; //思路1 vector<vector<int> > levelOrder(TreeNode *root){ vector<vector<int> > result; queue<NodeWithLevel > q; q.push(NodeWithLevel(root, 0)); while(!q.empty()){ NodeWithLevel cur = q.front();q.pop(); TreeNode *t = cur.p; if(t != NULL){ if(result.size() <= cur.level) { vector<int> v; v.push_back(t->val); result.push_back(v); }else result[cur.level].push_back(t->val); q.push(NodeWithLevel(t->left, cur.level + 1)); q.push(NodeWithLevel(t->right, cur.level + 1)); } } return result; } };
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: struct NodeWithLevel{ TreeNode *p; int level; NodeWithLevel(TreeNode *pp, int l):p(pp), level(l){} }; //思路2 void levelOrder(TreeNode *root, int level, vector<vector<int> >&result) { if(!root) return ; if(result.size() <= level) { vector<int> v; v.push_back(root->val); result.push_back(v); }else result[level].push_back(root->val); levelOrder(root->left, level + 1, result); levelOrder(root->right, level + 1, result); } vector<vector<int> > levelOrder(TreeNode *root){ vector<vector<int> >result; levelOrder(root, 0, result); return result; } };
Leetcode 树 Binary Tree Level Order Traversal
时间: 2024-10-24 19:53:44