LeetCode107-二叉树的层次遍历 II

19 篇文章 0 订阅

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其自底向上的层次遍历为:

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

一、思路

(一)逆转层序遍历

先使用层序遍历,得到层序遍历的结果,将结果逆转即可

C++代码:

class Solution {
public:
	vector<vector<int>> levelOrderBottom(TreeNode* root) {
		vector<vector<int>> ans;
		queue<TreeNode *> list1,list2;
		if (root == NULL)
			return ans;
		
		list1.push(root);
		while (!list1.empty() || !list2.empty()) {
			vector<int> temp;

			while (!list1.empty()) {
				TreeNode* node = list1.front();
				list1.pop();
				temp.push_back(node->val);
				if (node->left)
					list2.push(node->left);
				if (node->right)
					list2.push(node->right);
			}
			if (!temp.empty()) {
				ans.push_back(temp);
				temp.clear();
			}

			while (!list2.empty()) {
				TreeNode* node = list2.front();
				list2.pop();
				temp.push_back(node->val);
				if (node->left)
					list1.push(node->left);
				if (node->right)
					list1.push(node->right);
			}
			if (!temp.empty())
				ans.push_back(temp);
		}
		reverse(ans);
		return ans;
	}
	
	void reverse(vector<vector<int>>& ans) {
		int j = ans.size() - 1, i = 0;
		while (i < j) {
			vector<int> temp = ans[i];
			ans[i] = ans[j];
			ans[j] = temp;
			i++;
			j--;
		}
	}
};

执行效率:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值