LeetCode_107. Binary Tree Level Order Traversal II

Posted denggelin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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,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;
	

 

以上是关于LeetCode_107. Binary Tree Level Order Traversal II的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]题解(python):107-Binary Tree Level Order Traversal II

LeetCode107. Binary Tree Level Order Traversal II 解题报告

Leetcode 107 Binary Tree Level Order Traversal II

LeetCode107 Binary Tree Level Order Traversal II

Leetcode 107. Binary Tree Level Order Traversal II

LeetCode 107.Binary Tree Level Order Traversal II