Binary tree problem (print binary tree, binary tree substructure, mirror, traverse, binary tree satisfying path)

Source: Internet
Author: User
Tags bool int size

Title one: Print binary tree from top down

Each node of the two-fork tree is printed from top to bottom, and the same-level node prints from left to right.

The topic Analysis: This problem actually examines the tree traversal algorithm, the traversal usually has the preface, the middle order, the post-order traversal, this question examines the level traversal.

1, we need to use the queue, the implementation of print by layer, first put the root node in the queue, and the value of the root node into the vector;

2, determine whether the root node Zuozi is empty, not empty the node into the queue;

3, determine whether the right subtree of the root node is empty, not empty the node into the queue;

Loop read the node in the queue, and the node to make the decision of the left and right subtree, until the queue does not exist in the node;

The structure of the binary tree is as follows:

struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode (int x):
			val (x), left (null), right (null) {
	}
};
The subject code looks like this:

Class Solution {public
:
    vector<int> printfromtoptobottom (treenode* root) {
        vector<int> Printtreenode;
        Borrowing queues for hierarchical traversal
        queue<treenode*> pTree;
        if (root = NULL)  return printtreenode;
        else
        {   Ptree.push (root);
            while (!ptree.empty ())
            {
                TreeNode * proot = Ptree.front ();
                Printtreenode.push_back (proot->val);
                Ptree.pop ();                
                if (proot->left! = NULL) {Ptree.push (proot->left);}
                if (Proot->right!=null) {Ptree.push (proot->right);}                    
            }
        }            
       return printtreenode;
    }
;


Recursive and non-recursive forms of binary Tree's pre-order, middle-sequence and post-order traversal
Detailed Analysis Reference: http://www.cnblogs.com/SHERO-Vae/p/5800363.html


Topic 2:2 Sub-structure of the fork tree

Enter two binary trees, a, B, to determine whether a is a sub-structure of a. (PS: We agree that an empty tree is not a sub-structure of any tree)

If the structure of a subset of the subtree in a is the same as B, B is a sub-structure

Find the root node of B in a tree position, and then use recursive method to traverse, in the interview if there is no special requirements, the tree traversal can be used recursive way.

Class Solution {public
:
    bool Hassubtree (treenode* pRoot1, treenode* pRoot2)
    {  bool result = false;        
       if (pRoot1! = NULL && PRoot2! = null)
       {
           return doestree1havetree2 (proot1,proot2) | | Hassubtree (proot1->left,proot2) | | Hassubtree (Proot1->right,proot2);                }
       Return result;//If one of the nodes is empty, return false
    }
    bool  doestree1havetree2 (treenode* proot1,treenode* pRoot2)// Define a function to match two tree nodes
    {
        //If TREE2 traversal is complete, the value corresponds to the If
        (PRoot2 = = NULL) {return true) containing this subtree.
        If Tree2 has finished traversing, Tree1 has ended, then this subtree is not included
        if (pRoot1 = = NULL) {return false;}  
        If the value is different, it returns false
        if (proot1->val! = Proot2->val) {return false;}
        On the root node match, the left and right subtree are matched separately
        return doestree1havetree2 (proot1->left,proot2->left) && Doestree1havetree2 (proot1->right,proot2->right);
        The left and right sub-tree must match
     }
};


title 3:2 image of the fork Tree

operates a given two-fork tree and transforms it into a mirror of the source binary tree

Image definition of binary tree: source binary tree 
    	    8
    	   /  \ 6 x
    	 /\  /\
    	5  7 9
    	Mirror binary tree
    	    8
    	   /  \   6
    	 /\  /\
    	9 7  5
Image is to exchange the left and right sub-trees of the two-fork tree, which can be exchanged by recursive and non-recursive methods.

the recursive method is as follows:

Class Solution {public
:
    void Mirror (TreeNode *proot) {
        //mirror is to swap left and right subtrees
        if (proot = = NULL) return;< C26/>if (proot)
        {
             TreeNode * temp = proot->left;
             Proot->left = proot->right;
             Proot->right = temp;
             Mirror (proot->left);
             Mirror (Proot->right);}}
;
the non-recursive method is as follows:

The non-recursive method, the left and right sub-tree should be in advance and the root node of the same as the same as the tree of the exchange, if both sides in a cycle to assign value to the root node,
There's got to be a cover. These two nodes can be filled with stack,queue,vector and other containers, and then loop-switched
Using queue method to realize non-recursion

Class Solution {public
:
    void Mirror (TreeNode *proot) {
         if (proot = = NULL) return;
         Queue<treenode *> Treequeue;
         Treequeue.push (proot);
         while (!treequeue.empty ())
         {
             TreeNode *root = Treequeue.front ();
             TreeNode *temp = root->left;
             Root->left = root->right;
             Root->right = temp;
             if (root->left)
             {
                  treequeue.push (root->left);
             }
             if (root->right)
             {
                  treequeue.push (root->right);
             }
             Treequeue.pop ();}}
;

topic 4:2 The sequential traversal of the search tree

Title: Enter an array of integers to determine if the array is the result of a sequential traversal of a binary search tree. If yes, output yes, otherwise output No.

Assume that any two digits of the input array are different

Topic Analysis: Two forks search tree node Value law is: Left < root < right

The sequence of sequential traversal, the last value is the root node, and the value of the small root node belongs to the left subtree, and the value greater than the root node belongs to the right subtree

Recursive method: The recursive method of this problem is better understood

1, first the entire binary tree root node found, the left subtree into an array, the right subtree into an array;

2, then the array of left and right sub-tree recursive call this method;

3, when the result of two subtree invocation is true, the result is true;

The code is as follows:

Class Solution {Public:bool verifysquenceofbst (vector<int> sequence) {//Recursive method if (Sequen
        Ce.size () = = 0) {return false;}
        int length = Sequence.size ();
         int root = sequence[length-1];
         Vector<int> Lefttree;  
        Vector<int> Righttree;
        int i = 0;
                For (I;i < length-1;i++)//Exclude root node, so the upper limit is less than length-1 {if (sequence[i] > root) {
        break;//when the node value is greater than the root node, the left subtree is closed, exiting the loop} lefttree.push_back (Sequence[i]);  } for (int j = i; J < Length-1; J + +)//Exclude root node, so the upper limit is less than length-1 {if (Sequence[j] < Root) {return false;//when the right subtree appears with the value of a small root node, an error occurs, not the result of a post-step traversal} Righttree.pus
        H_back (Sequence[j]);
        bool left = true and right = true; if (lefttree.size () > 0) {left = Verifysquenceofbst (Lefttree);}//Determine if the value of the subtree is empty, or null, no further calls to the IF (rightTree.size () > 0) {right = Verifysquenceofbst (Righttree);} 
    Return (left && right); }
};
the non-recursive approach is simple and well understood,Because the search binary tree post-order traversal is regular, the previous part is less than the last value, the latter part is greater than the last value, as long as the next part is less than the case, it means that the array is a search binary tree traversal, and the above recursive method to make the same, just do not divide by the rules Saozi right subtree But each node is the root node, his left side is the left subtree, the right side is the right child tree. If the right subtree appears smaller than the root node, the value is not correct.

The code looks like this:

Class Solution {public
:
    bool Verifysquenceofbst (vector<int> sequence) {       
        int size = Sequence.size ();
        if (size = = 0) return false;
        int i = 0;
        while (--size)
        {
            while (Sequence[i] < sequence[size]) {i++;}
            while (Sequence[i] > Sequence[size]) {i++;}
            if (i < size)  {return false;}
            i = 0;              
        }
        return true;
    }
};

Topic 5:2 Fork Tree and path for a certain tree

Title Description: Enter a binary tree and an integer to print out all paths for the value of the node in the two-fork tree and for the input integer.

a path is defined as a path from the root node of the tree down to the node through which the leaf nodes go.

The subject examines depth-first traversal, which can take the form of recursion and non-recursion.

The non-recursive code is as follows:

Class Solution {public:vector<vector<int>> pathnum; 
     Vector<int> Pathvalue; Vector<vector<int>> Findpath (treenode* root,int expectnumber) {if (root = NULL) retur 
        n Pathnum;
        Non-recursive method, using the non-recursive form of first order traversal to stack<treenode*> Stacktree;
        treenode* cur = root;                     
        treenode* last = NULL;        
        int sum = 0; while (cur | |!stacktree.empty ()) {while (cur)//depth first, traverse left child {pathvalue.push_back (cur->val
                    ); 
                    sum = sum + pathvalue.back (); 
                    Stacktree.push (cur);
                       if (sum = = Expectnumber && Cur->right = = NULL && Cur->left = = null) {                                      
                    Pathnum.push_back (Pathvalue); 
                } cur = cur->left; } if (cur = = NULL) {treenode* temp = stacktree.top (); 
                    This condition judgment is the main problem, before going to Zuozi to determine if this node is the same as the previous node if (temp->right! = NULL && temp->right! = last) 
                     {cur = temp->right; } else if (!pathvalue.empty ()) {last =
                       Temp
                       Stacktree.pop ();
                       sum = Sum-pathvalue.back ();                    
                    Pathvalue.pop_back ();                                                                                           
            } 
                 }
    } return pathnum; }
};
The recursive code is as follows:

Class Solution {public
:
     vector<vector<int>> pathnum;
     Vector<int> Pathvalue; 
     Vector<vector<int>> Findpath (treenode* root,int expectnumber) {                
        if (root = NULL) return pathnum; 
        Recursive method
        if (root)
        {
            dfs (root,expectnumber);           
        }            
        return pathnum;
    }
    Depth-first algorithm
    void Dfs (TreeNode * cur,int sum)
    {
        pathvalue.push_back (cur->val);
        if (Sum-cur->val = = 0 && Cur->left = = NULL && Cur->right = = null)
        {
            Pathnum.push_back ( Pathvalue);
         } else{        
        if (cur->left) {DFS (cur->left,sum-cur->val);}
        if (cur->right) {DFS (cur->right,sum-cur->val);}            
        }
       Pathvalue.pop_back ();
    }       
};


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.