二叉树遍历

树的节点结构:
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };

前序遍历非递归:

void PreOrderTraversal(BTNode* pRoot)
{
	vector<int> v;

	if (pRoot == nullptr)
		return v;

	stack<BTNode*> s;
	s.push(pRoot);
	while (!s.empty())
	{
		pRoot = s.top();
		v.push_back(pRoot->val);
		s.pop();
		
		if (pRoot->right)
		{
			s.push(pRoot->right);
		}
		if (pRoot->left)
		{
			s.push(pRoot->left);
		}
	}
	return v;
}

中序遍历非递归:

vector<int> inorderTraversal(TreeNode* root) {
        vector<int> v;
        if(root == nullptr)
            return v;
        stack<TreeNode*> s;
        s.push(root);
        TreeNode *p;
        while(!s.empty())
        {
            while(p = s.top())
                s.push(p->left);
            s.pop();
            if(!s.empty())
            {
                p = s.top();
                s.pop();
                v.push_back(p->val);
                s.push(p->right);
            }
        }
        return v;
    }

层序遍历队列实现:


class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
         vector<vector<int>>v;
        if(root==nullptr)
        {
            return v;
        }
        queue<TreeNode*>q;
        q.push(root);
       while(!q.empty())
       {
           int sz=q.size();
           vector<int>temp;
           for(int i=0;i<sz;++i)
           {  
               root=q.front();
               temp.push_back(root->val);
               q.pop();
               if(root->left)
               {
                   q.push(root->left);
               }
               if(root->right)
               {
                   q.push(root->right);
               }
           }
           v.push_back(temp);
       }
        //while(!q.empty())
        //{
        //    vector temp;
        //    root = q.front();
        //    temp.push_back(root->val);
        //    if(root->left)
        //        q.push(root->left);
        //    if(root->right)
        //        q.push(root->right);
        //    q.pop();
        //    v.push_back(temp);
        //}   不能A 每一层分开保存.
        
        return v;
        
    }
};

二叉树镜像:
递归:

TreeNode* invertTree(TreeNode* root) {
        
        if(root)
        {
            swap(root->left,root->right);
            invertTree(root->left);
            invertTree(root->right);
        }
        return root;
    }

非递归:

TreeNode* invertTree(TreeNode* root) {
        if(nullptr == root)
            return root;
        queue<TreeNode*>q;
        q.push(root);
        TreeNode* p;
        while(!q.empty())
        {  
            p=q.front();
            swap(p->left,p->right);
            
            if(p->left)
            {
                q.push(p->left);
            }
            if(p->right)
            {
                q.push(p->right);
            }
            q.pop();
       } 
        return root;
    }

你可能感兴趣的:(成长之路,数据结构)