首页 > 代码库 > Leetcode bfs&dfs Binary Tree Postorder Traversal
Leetcode bfs&dfs Binary Tree Postorder Traversal
Binary Tree Level Order Traversal
Total Accepted: 20571 Total Submissions: 66679My SubmissionsGiven 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,记录指针向节点的指针和每个节点所在的层
思路2:dfs
递归函数:
void levelOrder(TreeNode *root, int level, vector<vector<int> >&result)
表示把根为root的树按层存放在result中,其中level表示当前的层数
复杂度:
bfs 时间O(n) ,空间O(n)
dfs 时间O(n) ,空间O(log n)
/** * 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; } }; 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 bfs&dfs Binary Tree Postorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。