[LeetCode] 103. Binary Tree Zigzag Level Order Traversal 二叉树的之字形层序遍历
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
102. Binary Tree Level Order Traversal 的变形,不同之处在于一行是从左到右遍历,下一行是从右往左遍历,交叉往返的之字形的层序遍历。
Java:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List <Integer>> result = new ArrayList<List<Integer>>(); ArrayList<TreeNode> q = new ArrayList<TreeNode>(); ArrayList<Integer> level = new ArrayList<Integer>(); if (root == null){ return result; } q.add(root); level.add(0); while (q.size() > 0){ TreeNode node = q.remove(0); int cl = level.remove(0); if (result.size() <= cl){ result.add(new ArrayList<Integer>()); } if (cl % 2 == 0){ result.get(cl).add(node.val); } else{ result.get(cl).add(0, node.val); } if (node.left != null){ q.add(node.left); level.add(cl + 1); } if (node.right != null){ q.add(node.right); level.add(cl + 1); } }//while return result; }//zigzag }
Python:
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @return a list of lists of integers def zigzagLevelOrder(self, root): if root is None: return [] result, current, level = [], [root], 1 while current: next_level, vals = [], [] for node in current: vals.append(node.val) if node.left: next_level.append(node.left) if node.right: next_level.append(node.right) if level % 2: result.append(vals) else: result.append(vals[::-1]) level += 1 current = next_level return result
C++:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int> > zigzagLevelOrder(TreeNode *root) { vector<vector<int> >res; if (!root) return res; stack<TreeNode*> s1; stack<TreeNode*> s2; s1.push(root); vector<int> out; while (!s1.empty() || !s2.empty()) { while (!s1.empty()) { TreeNode *cur = s1.top(); s1.pop(); out.push_back(cur->val); if (cur->left) s2.push(cur->left); if (cur->right) s2.push(cur->right); } if (!out.empty()) res.push_back(out); out.clear(); while (!s2.empty()) { TreeNode *cur = s2.top(); s2.pop(); out.push_back(cur->val); if (cur->right) s1.push(cur->right); if (cur->left) s1.push(cur->left); } if (!out.empty()) res.push_back(out); out.clear(); } return res; } };
类似题目:
[LeetCode] 102. Binary Tree Level Order Traversal 二叉树层序遍历
All LeetCode Questions List 题目汇总