LeetCode 102. Binary Tree Level Order Traversal
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 102. Binary Tree Level Order Traversal相关的知识,希望对你有一定的参考价值。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int>> levelOrder(TreeNode* root) { 13 vector<vector<int>> res; 14 vector<int> level; 15 if(!root) return res; 16 17 queue<TreeNode*> q1,q2; 18 q1.push(root); 19 while(!q1.empty()){ 20 while(!q1.empty()){ 21 TreeNode* cur = q1.front(); 22 q1.pop(); 23 level.push_back(cur->val); 24 if(cur->left) q2.push(cur->left); 25 if(cur->right) q2.push(cur->right); 26 } 27 res.push_back(level); 28 level.clear(); 29 q1.swap(q2); 30 31 } 32 return res; 33 } 34 };
和之前的某题类似,维护两个queue(不是stack因为不是zigzag),q1存当前层的节点,q2存下一层节点。
另一种写法:(java)
1 public class Solution { 2 public List<List<Integer>> levelOrder(TreeNode root) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>(); 4 if (root == null) 5 return res; 6 Queue<TreeNode> q = new LinkedList<TreeNode>(); 7 q.offer(root); 8 while (!q.isEmpty()) { 9 List<Integer> tmp = new ArrayList<Integer>(); 10 int size = q.size(); 11 for (int i = 0; i < size; ++i) { 12 TreeNode t = q.poll(); 13 if (t.left != null) 14 q.offer(t.left); 15 if (t.right != null) 16 q.offer(t.right); 17 tmp.add(t.val); 18 } 19 res.add(tmp); 20 } 21 return res; 22 } 23 }
新写法:(留坑)
1 public class Solution { 2 public List<List<Integer>> levelOrder(TreeNode root) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>(); 4 dfs(res,root,0); 5 return res; 6 } 7 public void dfs(List<List<Integer>> list,TreeNode node,int deep){ 8 if(node==null)return; 9 if(list.size()==deep) 10 list.add(new ArrayList<Integer>()); 11 list.get(deep).add(node.val); 12 dfs(list, node.left, deep+1); 13 dfs(list, node.right, deep+1); 14 } 15 }
以上是关于LeetCode 102. Binary Tree Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 102. Binary Tree Level Order Traversal
[LeetCode]题解(python):102- Binary Tree Level Order Traversal
LeetCode 102. Binary Tree Level Order Traversal
Leetcode 102. Binary Tree Level Order Traversal