LeetCode_107. Binary Tree Level Order Traversal II

 

107. Binary Tree Level Order Traversal II

Easy

Given a binary tree,return the bottom-up level order traversal of its nodes‘ values. (ie,from left to right,level by level from leaf to root).

For example:
Given binary tree [3,9,20,null,15,7],

    3
   /   9  20
    /     15   7

 

return its bottom-up level order traversal as:

[
  [15,7],[9,20],[3]
]

 

package leetcode.easy;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class BinaryTreeLevelOrderTraversalII {
	@org.junit.Test
	public void test() {
		TreeNode tn11 = new TreeNode(3);
		TreeNode tn21 = new TreeNode(9);
		TreeNode tn22 = new TreeNode(20);
		TreeNode tn33 = new TreeNode(15);
		TreeNode tn34 = new TreeNode(7);
		tn11.left = tn21;
		tn11.right = tn22;
		tn21.left = null;
		tn21.right = null;
		tn22.left = tn33;
		tn22.right = tn34;
		tn33.left = null;
		tn33.right = null;
		tn34.left = null;
		tn34.right = null;
		System.out.println(levelOrderBottom1(tn11));
		System.out.println(levelOrderBottom2(tn11));
	}

	// DFS solution:
	public List<List<Integer>> levelOrderBottom1(TreeNode root) {
		List<List<Integer>> wrapList = new LinkedList<List<Integer>>();
		levelMaker(wrapList,root,0);
		return wrapList;
	}

	private static void levelMaker(List<List<Integer>> list,TreeNode root,int level) {
		if (root == null) {
			return;
		}
		if (level >= list.size()) {
			list.add(0,new LinkedList<Integer>());
		}
		levelMaker(list,root.left,level + 1);
		levelMaker(list,root.right,level + 1);
		list.get(list.size() - level - 1).add(root.val);
	}

	// BFS solution:
	public List<List<Integer>> levelOrderBottom2(TreeNode root) {
		Queue<TreeNode> queue = new LinkedList<TreeNode>();
		List<List<Integer>> wrapList = new LinkedList<List<Integer>>();
		if (root == null) {
			return wrapList;
		}
		queue.offer(root);
		while (!queue.isEmpty()) {
			int levelNum = queue.size();
			List<Integer> subList = new LinkedList<Integer>();
			for (int i = 0; i < levelNum; i++) {
				if (queue.peek().left != null) {
					queue.offer(queue.peek().left);
				}
				if (queue.peek().right != null) {
					queue.offer(queue.peek().right);
				}
				subList.add(queue.poll().val);
			}
			wrapList.add(0,subList);
		}
		return wrapList;
	}
}

相关文章

自1998年我国取消了福利分房的政策后,房地产市场迅速开展蓬...
文章目录获取数据查看数据结构获取数据下载数据可以直接通过...
网上商城系统MySql数据库设计
26个来源的气象数据获取代码
在进入21世纪以来,中国电信业告别了20世纪最后阶段的高速发...