【Leetcode】Binary Tree Level Order Traversal II

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

题目:

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,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

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

思路:

定义一个方法 根据传入的层数返回该层所有结点。自下而上的查找各层结点。

算法:

	public List<List<Integer>> levelOrderBottom(TreeNode root) {
		int height = heightTree(root);
		List<List<Integer>> lists = new ArrayList<List<Integer>>();
		for (int i = height; i > 0; i--) { //自下而上
			List<Integer> list = new ArrayList<Integer>();
			list = kLevelNumber(root, 1, list, i);
			lists.add(list);
		}
		return lists;
	}

	public int heightTree(TreeNode p) {
		if (p == null)
			return 0;
		int h1 = heightTree(p.left);
		int h2 = heightTree(p.right);
		return h1 > h2 ? h1 + 1 : h2 + 1;
	}

	/**
	 * 返回kk层所有结点 
	 */
	public List<Integer> kLevelNumber(TreeNode p, int height, List<Integer> list, int kk) {
		if (p != null) {
			if (height == kk) {
				list.add(p.val);
			}
			list = kLevelNumber(p.left, height + 1, list, kk);
			list = kLevelNumber(p.right, height + 1, list, kk);
		}
		return list;
	}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yeqiuzs/article/details/49965231
个人分类: leetcode
所属专栏: Leetcode题解java版
上一篇【Leetcode】Populating Next Right Pointers in Each Node II
下一篇【Leetcode】Binary Search Tree Iterator
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭