LeetCode107 Binary Tree Level Order Traversal II

详细见:leetcode.com/problems/binary-tree-level-order-traversal-ii


Java Solution: github

package leetcode;

import java.util.Iterator;

/*
 * 	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]
	]
 */

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

import tools.TreeNode辅助.TreeNode;

public class P107_BinaryTreeLevelOrderTraversalII {
	static int N = Integer.MIN_VALUE;
	public static void main(String[] args) {
		TreeNode root = null;
		List<List<Integer>> ans = null;
		root = tools.TreeNode辅助.A_生成满二叉树(new int[] {
			1,
			2, 3,
			4, 5, 6, 7
		});
		root = tools.TreeNode辅助.A_生成满二叉树(new int[] {
			3,
			9, 20,
			N, N, 15, 7
		});
		root = tools.TreeNode辅助.A_生成满二叉树(new int[] {
			3
		});
		ans = new Solution().levelOrderBottom(root);
		System.out.println(ans.size());
		Iterator<List<Integer>> it = ans.iterator();
		while (it.hasNext()) {
			tools.Utils.B_打印List_Integer_OneLine(it.next());
		}
	}
	/*
	 * 	AC
	 * 	3 ms
	 */
	static class Solution {
		List<List<Integer>> ans = new LinkedList<>();
	    public List<List<Integer>> levelOrderBottom(TreeNode root) {
	        if (root == null) {
	        	return ans;
	        }
	    	Queue<TreeNode> q1 = new LinkedList<TreeNode>();
	    	Queue<Integer> q2 = new LinkedList<Integer>();
	    	q1.add(root);
	    	q2.add(1);
	    	int pre_int = -1;
	    	List<Integer> list_root = null;
	        while (! q1.isEmpty()) {
	        	TreeNode root_now = q1.poll();
	        	int root_int = q2.poll();
	        	if (root_int != pre_int) {
	        		if (pre_int != - 1) {
	        			ans.add(0, list_root);
	        		}
	        		pre_int = root_int;
	        		list_root = new LinkedList<>();
	        	}
	        	list_root.add(root_now.val);
	        	if (root_now.left != null) {
	        		q1.add(root_now.left);
	        		q2.add(root_int + 1);
	        	}
	        	if (root_now.right != null) {
	        		q1.add(root_now.right);
	        		q2.add(root_int + 1);
	        	}
	        }
	        if (pre_int != -1 && list_root != null) {
	        	ans.add(0, list_root);
	        }
	    	return ans;
	    }
	}
}


C Solution: github

/*
    url: leetcode.com/problems/binary-tree-level-order-traversal-ii
    AC 3ms 28.85%
*/

#include <stdio.h>
#include <stdlib.h>

struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};

typedef struct TreeNode * ptn;
typedef struct TreeNode stn;

typedef int* T;
typedef struct al sal;
typedef struct al * pal;

struct al {
    int capacity;
    int size;
    T* arr;
};

pal al_init(int capacity) {
    pal l = (pal) malloc(sizeof(sal));
    if (capacity < 1) return NULL;
    l->arr = (T*) malloc(sizeof(T) * capacity);
    l->capacity = capacity;
    l->size = 0;
    return l;
}

void al_expand_capacity(pal l) {
    T* new_arr = (T*) malloc(sizeof(T) * (l->capacity * 2 + 1));
    int i = 0;
    for (i = 0; i < l->capacity; i ++)
        new_arr[i] = l->arr[i];
    free(l->arr);
    l->arr = new_arr;
    l->capacity = l->capacity * 2 + 1;
}

void al_add_last(pal l, T v) {
    if (l->capacity == l->size) al_expand_capacity(l);
    l->arr[l->size] = v;
    l->size ++;
}

void al_free_all(pal l) {
    int i = 0;
    for (i = 0; i < l->size; i ++)
        free(l->arr[i]);
    free(l->arr);
    free(l);
}

T* al_convert_to_array_free_l(pal l) {
    T* arr = l->arr;
    free(l);
    return arr;
}

typedef ptn V;
typedef struct sl ssl;
typedef struct sl * psl;

struct sl {
    int capacity;
    int size;
    V* arr;
};

psl sl_init(int capacity) {
    psl l = (psl) malloc(sizeof(ssl));
    if (capacity < 1) return NULL;
    l->arr = (V*) malloc(sizeof(V) * capacity);
    l->capacity = capacity;
    l->size = 0;
    return l;
}

void sl_expand_capacity(psl l) {
    V* new_arr = (V*) malloc(sizeof(V) * (l->capacity * 2 + 1));
    int i = 0;
    for (i = 0; i < l->capacity; i ++)
        new_arr[i] = l->arr[i];
    free(l->arr);
    l->arr = new_arr;
    l->capacity = l->capacity * 2 + 1;
}

void sl_add_last(psl l, V v) {
    if (l->capacity == l->size) sl_expand_capacity(l);
    l->arr[l->size] = v;
    l->size ++;
}

void sl_free_all(psl l) {
    free(l->arr);
    free(l);
}


void swap_psl(psl* l1, psl* l2) {
    psl l = *l1;
    *l1 = *l2;
    *l2 = l;
}

void swap_int_star(int** a, int** b) {
    int* c = *a;
    *a = *b;
    *b = c;
}

void reverse(pal l) {
    int i = 0, j = l->size - 1;
    while (i < j) {
        swap_int_star(&(l->arr[i]), &(l->arr[j]));
        i ++;
        j --;
    }
}

int** levelOrderBottom(ptn n, int** cn, int* rn) {
    psl l1 , l2 ;
    int i = 0, i2 = 0, *t = NULL; 
    pal l = NULL, ln = NULL;
    if (n == NULL) return NULL;
    l1 = sl_init(16);
    l2 = sl_init(16);
    l = al_init(16);
    ln = al_init(16);
    sl_add_last(l1, n);
    while (l1->size != 0) {
        t = (int*) malloc(sizeof(int) * l1->size);
        for (i = 0; i < l1->size; i ++)
            t[i] = l1->arr[i]->val;
        al_add_last(l, t);
        t = (int*) malloc(sizeof(int) * 1);
        t[0] = l1->size;
        al_add_last(ln, t);
        l2->size = 0;
        for (i = 0; i < l1->size; i ++) {
            if (l1->arr[i]->left != NULL)
                sl_add_last(l2, l1->arr[i]->left);
            if (l1->arr[i]->right != NULL)
                sl_add_last(l2, l1->arr[i]->right);
        }
        swap_psl(&l1, &l2);
    }
    sl_free_all(l1);
    sl_free_all(l2);
    *cn = (int*) malloc(sizeof(int) * ln->size);
    for (i = 0; i < ln->size; i ++)
        (*cn)[ln->size - 1- i] = ln->arr[i][0];
    al_free_all(ln);
    *rn = l->size;
    reverse(l);
    return al_convert_to_array_free_l(l);
}


Python Solution: github

#coding=utf-8

'''
    url: leetcode.com/problems/binary-tree-level-order-traversal-ii
    @author:     zxwtry
    @email:      zxwtry@qq.com
    @date:       2017年4月28日
    @details:    Solution: 56ms 59.43%
'''

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def levelOrderBottom(self, n):
        """
        :type n: TreeNode
        :rtype: List[List[int]]
        """
        if n == None: return []
        ans, l = [], [n]
        while len(l) != 0:
            ans.append([nn.val for nn in l])
            ll = []
            for nn in l:
                if nn.left != None: ll.append(nn.left)
                if nn.right != None: ll.append(nn.right)
            l = ll
        ans.reverse()
        return ans


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值