image.pnghttps://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
(图片来源https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
)
日期 | 是否一次通过 | comment |
---|---|---|
2020-03-15 | 0 |
递归
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) {
return res;
}
helper(root, res, 0);
return res;
}
private void helper(TreeNode root, List<List<Integer>> res, int level) {
if(root == null) {
return ;
}
if(level >= res.size()) {
res.add(new LinkedList<>()); // add(0,xxx)操作性能更优
}
List<Integer> temp = res.get(level);
if((level & 1) == 0) {
temp.add(root.val);
} else {
temp.add(0, root.val);
}
helper(root.left, res, level+1);
helper(root.right, res, level+1);
}
网友评论