Binary Tree Traversal application (path and question, judging whether it is a two-fork search tree, judging whether it is a two-fork balance tree)

Source: Internet
Author: User

Now it becomes more and more that the problem of trees is so changeable that it is a new problem to change a condition casually.


A binary tree path problem by First order traversal


Problem: A binary tree Each node contains an integer, design an algorithm to output all paths that satisfy the condition: the sum of all nodes on this path equals the given value. Note Such paths do not require that the root node be required to start.


If there is no last condition, the question is seen above the Leetcode, which is to take the way of first order traversal and record the path. But with the last condition, you need to turn the corner and think about it.


Of course, you also need to record the path, and remember to backtrack. In addition to not requiring this condition to start from the root node, you can think like this, each time you traverse to the current node, look for the path from the path that contains the eligible partial subarray of the current node and for the given value.


Tree node information class treenode{public:int data; TreeNode * LEFT; treenode* right; TreeNode (int d,treenode * L=null,treenode * r=null) {data=d;left=l;right=r;}};/ /print output data void PrintA (vector<int> vec,int lev1,int lev2) {for (int i=lev1;i<=lev2;i++) {cout<<vec[i]< < "";} Cout<<endl;} void Findsum (TreeNode * head,int sum,vector<int> &buffer,int level) {if (head==null) return; int tmp=sum;// The current node data is added to the buffer buffer.push_back (head->data);//Note this processing mode, which is different from the root node to the current node and for the specified value in addition to this problem for (int i=level;i>=0;i--) {tmp-=buffer[i];if (tmp==0) {PrintA (buffer,i,level);}} Access left subtree findsum (head->left,sum,buffer,level+1);//Access Right subtree findsum (head->right,sum,buffer,level+1);// Note that backtracking occurs when both the left and right subtrees are traversed//backtracking refers to the processing buffer.pop_back () to be done when exiting the current node;}

The buffer parameter passed by the Findsum method above is a reference and takes the form of a first-order traversal. So the last line of code is the backtracking process. If the buffer parameter is not a reference, then backtracking is not required.

The understanding of backtracking can be deepened in both ways. Obviously the above one is much more efficient than the code below, but there is no need to take this much into account when the code above is backtracking and if it needs to be handled well.

void Findsum (TreeNode * head,int sum,vector<int>  buffer,int level) {if (head==null) return; int tmp=sum;// The current node data is added to the buffer buffer.push_back (head->data);//Note this processing mode, which is different from the root node to the current node and for the specified value in addition to this problem for (int i=level;i>=0;i--) {tmp-=buffer[i];if (tmp==0) {PrintA (buffer,i,level);}} Access left subtree findsum (head->left,sum,buffer,level+1);//Access Right subtree findsum (head->right,sum,buffer,level+1);// Note that backtracking occurs when both the left and right subtrees are traversed//backtracking refers to the processing that is done when exiting the current node///If buffer is not a reference, no backtracking is required, and there is no need to add backtracking code between the left and right sub-trees above This is because the modification of the buffer when accessing Zuozi does not affect the content of buffer when accessing the right subtree//buffer.pop_back ();}

Use the following test cases:

int main () {TreeNode * t1=new TreeNode (-2); TreeNode * t2=new TreeNode (3,T1); TreeNode * t3=new TreeNode (1); TreeNode * t4=new TreeNode (2,T2,T3);vector<int> buffer;findsum (t4,3,buffer,0); GetChar (); return 0;}

The shape of the tree is as follows:


Program output:



Sequence traversal to determine whether a tree is a two-fork sort tree

How to tell if a binary tree is a sort tree?

In order to determine whether a tree is a binary sort tree, the result of the middle sequence traversal of the binary sort tree is the characteristic from small to large ordered. Of course, you can use an array to record the path, and then determine if the elements in the array are sorted, but there is a space overhead for O (n). There is a way to compare directly in the traversal process, which is to define a variable to hold the value of the previous accessed node.

From this example, we can learn how to save the value of the previous Access node, can be implemented by global variables or references, I use the reference, of course, global variables can also.

This example notes how to save the previous access node, which is implemented by reference//or by a global variable to implement BOOL Judgesorted (TreeNode * Root,int & Pre) {if (root==null) Return true;//determines if the left subtree is not a balanced bool left=judgesorted (ROOT->LEFT,PRE);//If Zuozi is not balanced or the value of the previous node is greater than the current node, then return to Falseif (!left| | Pre> Root->data) return false;pre=root->data;//need to update the pre value after accessing the current node so that when traversing the right subtree, the pre is the current node return judgesorted ( ROOT->RIGHT,PRE);}

or using the binary tree above, you can find that the result returns false, if the above node 3 and 1 are exchanged, then the result is true.



Sequential traversal to determine whether a tree is a balanced binary tree

Judge if a tree is a balanced binary tree?

Judge whether a tree is a balanced binary tree can be used in the first sequence traversal, each traversal to a node, calculate the depth of its left and right subtree, compare their depth difference, if the depth difference is less than 1, then traverse the Saozi, so that has been recursive, but this method is very low efficiency, because there is a lot of repetition.


Using the post-order traversal can avoid the above duplication problem, the use of sequential traversal traversal of the binary tree every traversal to a node before it has traversed its left and right sub-tree, as long as the traversal to each node recorded its height, you can avoid the above sequence over a large number of repeated operations.

Traverse the binary tree bool Isbalance (TreeNode * Root,int &depth) {if (root==null) {Depth=0;return true;} int left,right;//first accesses the left subtree, then accesses the right subtree if (isbalance (root->left,left) &&isbalance (root->right,right)) {// If the left and right subtrees are balanced, then it is necessary to compare the height difference of the left-right sub-tree, if the height difference is less than 1, then the sub-tree with this node as the root node is the balanced int diff=left-right;if (diff>=-1& &diff<=1) {Depth=max (left,right) +1;return true;}} return false;}

                         ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                                            



Finally there is a more ingenious way to solve the above problem, you can find the node with the lowest depth of the root node and the depth of the node, according to the difference between the two depths to determine whether the tree is a binary balance tree:

This is the most ingenious solution, but it's hard to think of.


The depth int maxheight (TreeNode * root) {if (root==null) return 0;return Max (MaxHeight (root->left), maxheight) of the farthest point of the distance root (Root->right)) +1;} The depth int minheight (TreeNode * root) {if (root==null) return 0;return min (minheight (root->left)) of the node closest to root is obtained, MinHeight (root->right)) +1;} BOOL Isbalance (TreeNode * root) {int diff=maxheight (root)-minheight (root); return diff>=-1&&diff<=1;}




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Binary Tree Traversal application (path and question, judging whether it is a two-fork search tree, judging whether it is a two-fork balance tree)

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.