码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode_107. Binary Tree Level Order Traversal II

时间:2019-10-01 12:19:17      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:out   root   ali   system   static   roo   etc   order   otto   

 

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

标签:out   root   ali   system   static   roo   etc   order   otto   

原文地址:https://www.cnblogs.com/denggelin/p/11614887.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!