标签:c++ arraylist node 思路 val reverse int null time
一:解题思路
Time:O(n),Space:O(n)
二:完整代码示例 (C++版和Java版)
C++:
class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> result; if (root == NULL) return result; bool right2Left = false; queue<TreeNode*> q; q.push(root); while (!q.empty()) { int size = q.size(); vector<int> elem; for (int i = 0; i < size; i++) { TreeNode* node = q.front(); q.pop(); elem.push_back(node->val); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); } if (right2Left) reverse(elem.begin(),elem.end()); result.push_back(elem); right2Left = !right2Left; } return result; } };
Java:
class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> result=new ArrayList<>(); if(root==null) return result; boolean right2Left=false; Queue<TreeNode> q=new LinkedList<>(); q.add(root); while (!q.isEmpty()) { int size=q.size(); List<Integer> elem=new ArrayList<>(); for(int i=0;i<size;i++) { TreeNode node=q.poll(); elem.add(node.val); if(node.left!=null) q.add(node.left); if(node.right!=null) q.add(node.right); } if(right2Left) Collections.reverse(elem); result.add(elem); right2Left=!right2Left; } return result; } }
p141 二叉树的 Z 字形遍历(leetcode 103)
标签:c++ arraylist node 思路 val reverse int null time
原文地址:https://www.cnblogs.com/repinkply/p/12722968.html