二叉树的遍历

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zy704599894/article/details/79952875

二叉树的前序遍历:

/**
 * 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<int> preorderTraversal(TreeNode* root) 
    {
        vector<TreeNode*>p;
		vector<int>v;
		TreeNode *x = root;
		while (x != NULL || p.size() != 0)
		{
			v.push_back(x->val);
			if (x->right != NULL)
				p.push_back(x->right);
			x = x->left;
			if (x == NULL&&p.size())
			{
				x = p.back();
				p.pop_back();
			}
		}
        return v;
    }
};

中序遍历二叉树:

/**
 * 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<int> inorderTraversal(TreeNode* root) 
    {
        vector<TreeNode*>p;
		vector<int>v;
		if (root == NULL) return v;
		TreeNode *x = root;
		while (x != NULL || p.size() != 0)
		{
			if (x != NULL)
			{
				p.push_back(x);
				x = x->left;
			}
			else
			{
				x = p.back(), p.pop_back();
				v.push_back(x->val);
				x = x->right;
			}
		}
		return v;
    }
};

二叉树的后序遍历:

/**
 * 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<int> postorderTraversal(TreeNode* root)
    {
        vector<TreeNode*>p;
		vector<int>v;
		if (root == NULL) return v;
		TreeNode *x = root, *pre;
		do
		{
			while (x != NULL) /*先遍历根节点的左子树*/
			{
				p.push_back(x);
				x = x->left;
			}
			pre = NULL;
			while (p.size())
			{
				x = p.back(), p.pop_back();
				if (x->right == pre)  /*pre为上一个访问的节点,如果当前节点的右字数已经访问过,则访问根节点并更新pre*/
					pre = x,v.push_back(x->val);
				else  /*否则访问右子树*/
				{
					p.push_back(x);
					x = x->right;
					break;
				}
			}
		} while (p.size());
		return v;
    }
};

二叉树的层次遍历:

/**
 * 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)
    {
        queue<TreeNode*>q;
		vector<vector<int> >ans;
		vector<int>v;
		if (root == NULL) return ans;
		TreeNode *x = root;
		int rev = 1; /*当前层节点的个数*/
		q.push(x);
		while (!q.empty())
		{
			x = q.front(), q.pop(), rev--;
			v.push_back(x->val);
			if (x->left != NULL)
				q.push(x->left);
			if (x->right != NULL)
				q.push(x->right);
			if (rev == 0)  /*判断当前一层是否已经全部访问,如果全部访问,记录数据并访问下一层*/
			{
				rev = q.size();
				ans.push_back(v);
				v.clear();
			}
		}
		return ans;
    }
};


阅读更多
想对作者说点什么?

博主推荐

换一批

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