The basic operation of tree: four kinds of traversal

Preorder traversal recursive version

Programming ideas

That stack with the system less efficient. . Binary tree preorder traversal rules: 1 access to the root; 2. Traverse the left subtree; 3. Traverse the right subtree

Programming

//树的定义
struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
private:
    void rec(TreeNode* root,vector<int> &ret){
        if(root != nullptr){
            ret.push_back(root->val);
            rec(root->left,ret);
            rec(root->right,ret);
        }
    }
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> ret;
        rec(root,ret);
        return ret;
    }
};

Programming summary

Conventional methods use the reference vector attention.


 

Preorder traversal iteration edition

Programming ideas

Use of a secondary node p, in fact, such an approach can be seen as a template, as well as in the corresponding sequence and the subsequent stencil writing , forms very uniform, easy to remember.
P is initialized by the secondary root node, loop conditions while the stack is not empty or the secondary node p is not empty, the loop is first determined if the auxiliary node p exists, then the first added p stack, and then the added value of the node p res result, in which case p at the left child node. Otherwise, if p does not exist, indicating no left child node, we remove the top of the stack node, point to the right child node p stack node.

Programming

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> s;
        TreeNode *p = root;
        while (!s.empty() || p) {
            if (p) {
                s.push(p);
                res.push_back(p->val);
                p = p->left;
            } 
            else {
                TreeNode *t = s.top(); 
                s.pop();
                p = t->right;
            }
        }
        return res;
    }
};    

Topic summary

Under the premise master the law, using the template memory.


 

Preorder  recursive version

Programming ideas

That stack with the system less efficient. . Binary tree preorder traversal rules: 1. Traverse the left subtree; 2. access to the root; 3. Traverse the right subtree

Programming

class Solution {
private:
    void rec(TreeNode* root,vector<int> &ret){
        if(root != NULL){            
            rec(root->left,ret);
            ret.push_back(root->val);
            rec(root->right,ret);
        }
    }
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> ret;
        rec(root,ret);
        return ret;
    }
};

Topic summary

conventional.


Preorder  iterative version

Programming ideas

Using an auxiliary node p, in fact, such an approach can be seen as a template, as well as the corresponding preamble and the subsequent template writing , in the form of very unified, easy to remember.
Because the order of traversal sequence is the left - Root - the right, so that the preamble is different from the step of the node value added if the results from the mobile res to the else.
P is initialized by the secondary root node, loop conditions while the stack is not empty or the secondary node p is not empty, the loop is first determined if the presence of the secondary node p; p is added first then the stack, the p It points to the top node of the left child node. Otherwise, if p does not exist, indicating no left child node, we remove the top of the stack node, then the node p value added results res, in which case p points to its right child nodes.

Programming

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> s;
        TreeNode *p = root;
        while (!s.empty() || p) {
            if (p) {
                s.push(p);
                p = p->left;
            } 
            else {
                TreeNode *t = s.top(); 
                s.pop();
                res.push_back(t->val);
                p = t->right;
            }
        }
        return res;
    }
};    

Topic summary

Note that the difference between the front and traversing links, because the order of traversal sequence is the left - Root - the right, so that the preamble is different from the step of the node value added if the results from the mobile res to the else.


 

Postorder  recursive version

Programming ideas

That stack with the system less efficient. Preorder traversal of a binary tree rules: 1. Traverse the left subtree; 2 traversing right subtree; 3 access to the root node;.

Programming

class Solution {
private:
    void rec(TreeNode* root,vector<int> &ret){
        if(root != NULL){            
            rec(root->left,ret);
            rec(root->right,ret);
            ret.push_back(root->val);           
        }
    }
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> ret;
        rec(root,ret);
        return ret;
    }
};

Programming summary

conventional.


Postorder  iteration edition

Programming ideas

Using an auxiliary node p, in fact, such an approach can be seen as a template, as well as the corresponding preamble sequence and the template writing , in the form of very unified, easy to remember.
Since the order after order traversal is left - and right - the root, but the order preorder traversal of the root - left - right , but it is still both very similar, we can first do some small changes on the earlier order traversal method, making it traversal order becomes the root - Right - left, then flip it, is left - and right - the root . The inversion method, the result is added to the reverse res, every node added value at the beginning of res result, changes to the sequence preorder traversal of a change as long as the stack order, first left and right, so that the stack processing time It is the first right after the left. Be sure to pre-order traversal memory comparison! ! !

Development: When accessing a node * p, stack node happens to be the ancestors of all * p node. From the bottom of the stack to the bottom of the stack plus * p junction node, a path from the root node configured just to * p junction. This feature is important, such as seeking a path to the root node; the sum of two nodes recent common ancestor; available with this idea.

Programming

class Solution {
 public : 
    Vector < int > postorderTraversal (the TreeNode * the root) { 
        Vector < int > RES; 
        Stack <* the TreeNode> S; 
        the TreeNode * P = the root;
         the while (! s.empty () || P) {
             IF ( P) { 
                s.push (P); 
                res.insert (res.begin (), P -> Val);     // add back, forward and added to the preamble is 
                P = p-> right; // with the preamble Comparative 
            } 
            the else {
                TreeNode *t = s.top(); 
                s.pop();
                p = t->left;
            }
        }
        return res;
    }
};

Programming summary

It is important to expand the idea! !


 

Traverse the level version 1

Programming ideas

Routine traverse the level, need the help of a queue.
First root enqueue and dequeue, access to the root node, if it has a left subtree, then the left subtree root node enqueued, forming a lower layer; if it has the right subtree, then the right sub enqueue tree root, the next layer is formed. Then dequeued to the access node, and so forth, until the queue is empty. Look at the code easier to understand.
NOTE:
The basic operation of the queue are:
enqueued as Example: q.push (x); x to the end of the queue.
Dequeue, as described in Example: q.pop (); pop the first element of the queue, attention, and will not return value is the pop-up element.
The first team to access elements such cases: q.front (), that is the first to be pushed into the queue elements.
Access to the tail element, as described in Example: q.back (), i.e., the final element is pressed into the queue.
Analyzing empty queue, as described in Example: q.empty (), when the queue is empty, returns true.
The number of elements in the access queue, as described in Example: q.size ()

Programming

class Solution {
 public : 
    Vector <Vector < int >> levelOrder (the TreeNode * the root) { 
        
        Vector <Vector < int >> V; 
        Queue <the TreeNode *> Q; 
        q.push (the root);   // root enqueue 
        IF ( == the root NULL)  
             return V;
         the while ) {(q.empty (!)   // queue is not empty 
            Vector < int > VV; 
            queue <* the TreeNode> next;   //   create a second queue for storing the next layer node 
            the while (! q.empty ()) {  // traversing nodes of the current layer is the core of this layer other cycles are output in order to meet OJ 
                
                the TreeNode * Tre = q.front (); 
                vv.push_back (Tre -> Val);   // access the node, in order to meet the output requirements, it is somewhat complex, 
                q.pop ();   // head elements dequeue 
                IF (! tre-> left = NULL) {   // it has left subtree 
                    next.push (tre-> left); 
                } 
                IF (Tre -> right = NULL) {!   // it has a right subtree 
                    next.push (tre-> right); 
                }                 
            } 
            v.push_back (VV); 
            Q = Next;   // // iterate one after the entering 
        }
         return V; 
    } 
};

Programming summary

Traverse the level tend to use the queue, the queue to be familiar with the basic operation, pay attention to generate two-dimensional vector.


Traverse the level  version 2

Programming ideas

Given a binary tree, the node returns its value from the bottom-up hierarchy traversal. (Ie, by physical layer to the layer from the leaf nodes of the root node, layer by layer traversal from left to right).

A similar version of the same, but need a multi-stack, the return of each node added to the stack, the final output.

Programming

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>>v;
        stack<vector<int>>s;
        queue<TreeNode*>q;
        q.push(root);  //根节点入队
        if(root == NULL)  
            return v ;
        while(!q.empty()){  //队列不空
            vector<int>vv;
            queue<* The TreeNode> Next;   //   create a second queue node is used to store the next layer 
            
            the while (! Q.empty ()) {   // other traversing each node is the core of this layer is to meet cycle OJ output 
                
                the TreeNode * Tre = q.front (); 
                vv.push_back (Tre -> Val);   // access the node, in order to meet output requirements, it is somewhat complex, 
                q.pop ();   // head elements dequeue 
                IF (! tre-> left = NULL) {   // it has left subtree 
                    next.push (tre-> left); 
                } 
                IF (! tre-> right = NULL) {   // it has a right subtree 
                    next.push (tre-> right); 
                }
                
            } 
            S.push (VV);   // for each layer node stack
             // v.push_back (VV); 
            Q = Next;   //  // traverse into the next layer after 
        }
         the while (s.empty ()! ) {   // the reverse output nodes each 
            v.push_back (s.top ()); 
            s.pop (); 
        } 
        return V; 
    } 
};

Programming summary

Note that with the use of other data structures.

Guess you like

Origin www.cnblogs.com/parzulpan/p/11257376.html