【leetcode】二叉树的锯齿形层次遍历

题目要求

二叉树的锯齿形层次遍历

这个程序没写出来,摘抄了九章算法的代码,方便复习整理。
https://www.jiuzhang.com/solutions/binary-tree-zigzag-level-order-traversal/

核心思想

利用stack的办法解决。也可以用普通层次遍历的方法倒序输出。

完整代码如下

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 
 * 二叉树的锯齿形层次遍历
 *
 */
public class Solution {

	class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;
		TreeNode(int val) {
			this.val = val;
		}
	}
	
	public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
		List<List<Integer>> result = new ArrayList<List<Integer>>();
		if(root == null) {
			return result;
		}
		Stack<TreeNode> currLevel = new Stack<>();
		Stack<TreeNode> nextLevel = new Stack<>();
		Stack<TreeNode> temp ;
		currLevel.push(root); //入栈 
		boolean normalOrder = true;	//初始,即奇数层为简单层次遍历
		while(!currLevel.isEmpty()) {
			ArrayList<Integer> currLevelResult = new ArrayList<>();
			while(!currLevel.isEmpty()) {
				TreeNode node = currLevel.pop();
				currLevelResult.add(node.val);
			
				if(normalOrder) {
					if(node.left != null) {
						nextLevel.push(node.left);
					}
					if(node.right != null) {
						nextLevel.push(node.right);
					}
				} else {
					if(node.right != null) {
						nextLevel.push(node.right);
					}
					if(node.left != null) {
						nextLevel.push(node.left);
					}
				}
			}
			result.add(currLevelResult);
			temp = currLevel;
			currLevel = nextLevel; 
			nextLevel = temp;
			normalOrder = !normalOrder;
		}
		
		return result;
		
	}
	
}

你可能感兴趣的:(算法)