解题思路
bfs,在奇数层的时候,将该层所有的值进行翻转。
相关代码
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public TreeNode reverseOddLevels(TreeNode root) {Queue<TreeNode> queue = new LinkedList<>();if(root==null) return null;queue.add(root);int level=0;while(queue.isEmpty()==false){int len = queue.size();List<TreeNode> res = new ArrayList<>();for(int i=0;i<len;i++){TreeNode temp = queue.poll();if(temp.left!=null) queue.add(temp.left);if(temp.right!=null) queue.add(temp.right);res.add(temp);}if(level%2==1){for(int i=0;i<res.size()/2;i++){int temp = res.get(i).val;res.get(i).val = res.get(res.size()-i-1).val;res.get(res.size()-i-1).val = temp;}} level++;}return root;}
}