1. 程式人生 > >leetcode 102 Binary Tree Level Order Traversal

leetcode 102 Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

 

return its level order traversal as:

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

給定一個二叉樹,按層次輸出其節點,而且輸出的結果需體現其節點的層次資訊。二叉樹的問題基本都可以使用深度優先搜尋或廣度優先搜尋來解決,本題就是典型的廣度優先搜尋問題。核心是遍歷到新的層次時,需要壓入一個新的陣列,以後同一層級的節點都按左右順序壓入,遞迴版本程式碼如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
		vector<vector<int>> ret;
		bfsNodes(ret, 0, root);
		return ret;
	}

	void bfsNodes(vector<vector<int>> &ret, int level,  TreeNode* root)
	{
		if (NULL == root)
		{
			return;
		}
		if (ret.size() == level)//Attension: push new vector when traverse the most left node
		{
			ret.push_back({});
		}
		ret[level].push_back(root->val);//ret aready has element at level
		if (root->left)
		{
			bfsNodes(ret, level + 1, root->left);
		}
		if (root->right)
		{
			bfsNodes(ret, level + 1, root->right);
		}
	}
};

二叉樹的遍歷還有非遞迴的方式,這種方式是之前缺少練習的。這種情況下需要藉助一個佇列,遍歷每層的節點時,在該層遍歷該層節點數,每遍歷到一個節點時,將該節點彈出,記錄下該節點的值,同時壓進左右子節點,這樣遍歷下一層的節點時下層的節點數便是佇列的長度,如此直到佇列為空。非遞迴版本程式碼如下:

class Solution {
public:
	vector<vector<int>> levelOrder(TreeNode* root) {
		vector<vector<int>> ret;
		if (!root)
		{
			return ret;
		}
		queue<TreeNode*> q_node;
		q_node.push(root);
		while (!q_node.empty())
		{
			vector<int> v_level;
			int curr_size = q_node.size();	//record the number of current level
			for (int i = 0; i < curr_size; i++)
			{
				TreeNode* tmp_node = q_node.front();
				q_node.pop();
				if (tmp_node)
				{
					v_level.push_back(tmp_node->val);
					if (tmp_node->left)
					{
						q_node.push(tmp_node->left);
					}
					if (tmp_node->right)
					{
						q_node.push(tmp_node->right);
					}
				}
			}
			ret.push_back(v_level);
		}
		return ret;
	}
};