LeetCode--103. Binary Tree Zigzag Level Order Traversal

题目链接:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/

这个是接着上一篇写的,思路有点像,不过要添加一个标志符来判断是从左往右加入链表中,还是从右往左,这个跟上一篇差不多。我用的是层序数的奇偶性,也可以用逻辑变量。这里不赘述!

代码如下:

class Solution {
    public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    
		List<List<Integer>> ans=new LinkedList<List<Integer>>();
        if(root==null)
        	return ans;
		Queue<TreeNode> q=new LinkedList<TreeNode>();
		q.add(root);
		int nums=1;
		int next_nums=0;
		int depth=1;
		while(!q.isEmpty())
		{
			List<Integer> tmp_list=new LinkedList<Integer>();
			if(depth%2!=0)
			{
				for(int k=nums;k>0;k--)
				{
					TreeNode tmp=q.poll();
					tmp_list.add(tmp.val);
					if(tmp.left!=null)
					{
						q.add(tmp.left);
						next_nums++;
					}
					if(tmp.right!=null)
					{
						q.add(tmp.right);
						next_nums++;
					}
				}
			}
			else
			{
				for(int k=nums;k>0;k--)
				{
					TreeNode tmp=q.poll();
					tmp_list.add(0,tmp.val);
					if(tmp.left!=null)
					{
						q.add(tmp.left);
						next_nums++;
					}
					if(tmp.right!=null)
					{
						q.add(tmp.right);
						next_nums++;
					}
				}
			}
			ans.add(tmp_list);
			nums=next_nums;
			next_nums=0;
			depth++;
		}
		return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/To_be_to_thought/article/details/85684183
今日推荐