Binary tree concept programming questions

Corresponding letecode link:

snap

Topic description:

Given a binary tree root node root, determine whether it is a valid binary search tree.

An efficient binary search tree is defined as follows:

The left subtree of a node contains only numbers less than the current node.
The right subtree of a node contains only numbers greater than the current node.
All left and right subtrees must themselves be binary search trees.
 

Example 1:


Input: root = [2,1,3]
Output: true
Example 2:


Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The value of the root node is 5, but the value of the right child node is 4.
 

hint:

The number of nodes in the tree is in the range [1, 104]
-231 <= Node.val <= 231 - 1

 Problem solving ideas:

1. The value of the current node is the upper bound (maximum value) of the value of its left subtree
2. The value of the current node is the lower bound (minimum value) of the value of its right subtree,
so we introduce the upper and lower bounds here, using to save the maximum and minimum values ​​that occurred in the previous node

image.png

In each subtree, root is the upper bound of the left subtree and the lower bound of the right subtree. Only when these two are established at the same time, it is possible to ensure that it is a binary search tree. 

image.png

Corresponding code:

class Solution {
public:
    bool isValidBST(TreeNode* root) {
        return traversal(root,LONG_LONG_MIN,LONG_LONG_MAX);//由于题目说节点的值可以取到整型最大或者最小所以我们用long long 
    }
    bool traversal(TreeNode*root,long long min,long long max)
    {
              if(root==nullptr)//空树为true
              {
                  return true;
              }
              if(root->val<=min||root->val>=max)//不合法
              {
                   return false;
              }
         bool Leftret=  traversal(root->left,min,(long long)(root->val));//检查左子树
               if(!Leftret)return false;
         bool Rightret=traversal(root->right,(long long)(root->val),max);//检查右子树
         return Rightret;
         
    }
};

Of course, we can also use inorder traversal:

Define a preVal similar to a global variable, first check whether the left subtree is a search binary tree. When the left subtree is recursed, it is judged whether the value of the single previous node is less than or equal to preval, if so, return false, if not, give the value of the current node to preval. 

Corresponding code:

class Solution {
public:
         long long  preVal=LONG_LONG_MIN;
    bool isValidBST(TreeNode* root) {
               if(!root)return true;
               bool isLeftBST=isValidBST(root->left);//检查左子树是不是
               if(!isLeftBST){
                   return false;
               }
               if(root->val<=preVal){//不合法
                   return false;
               }else{
                   preVal=root->val;
               }
               return isValidBST(root->right);//检查右子树即可;

    }
};

 Iterative method:

Since the in-order traversal of the search binary tree is ordered, we can compare two adjacent numbers to see if they are ordered. After comparing the complete tree, the result comes out

class Solution {
public:
    bool isValidBST(TreeNode* root) {
           TreeNode*pre=nullptr;
           stack<TreeNode*>stk;
           TreeNode*cur=root;
           while(!stk.empty()||cur){
               while(cur){
                   stk.push(cur);
                   cur=cur->left;
               }
               auto node=stk.top();
               stk.pop();
               if((pre!=nullptr)&&node->val<=pre->val){//前面一个比后面一个大违法搜索二叉树的规则
                   return false;
               }
               pre=node;
               cur=node->right;
           }
           return true;
    }
};

Balanced Binary Tree

Corresponding letecode link:

snap

Topic description:

Given a binary tree, determine whether it is a highly balanced binary tree.

In this problem, a height-balanced binary tree is defined as:

The absolute value of the height difference between the left and right subtrees of each node of a binary tree does not exceed 1.

Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: true
Example 2:
Input: root = [1,2,2,3,3,null,null,4,4 ]
output: false
Example 3:

input: root = []
output: true

hint:

The number of nodes in the tree is in the range [0, 5000]
-104 <= Node.val <= 104

Problem solving ideas:

1. For the current node, find the depths of the left subtree and the right subtree respectively, and determine whether the height difference between the left and right subtrees is <=1.
2. Use the method of solving the depth of the binary tree in question 104.
3. Then do the same operation to the left subtree and right subtree of the current node.

Corresponding code:

class Solution {
public:
       int getdepth(TreeNode*root) {//求高度
           if(root==nullptr)
             return 0;
           int len1=getdepth(root->left);
           int len2=getdepth(root->right);
           return len1>len2?len1+1:len2+1;
       }

    bool isBalanced(TreeNode* root) {
            if(root==nullptr)
                return true;//空树为true;
     return abs(getdepth(root->left)-getdepth(root->right))<2&&isBalanced(root->left)&&isBalanced(root->right);
    }
};

 But this time replication degree is very high for 0 (N^2) repeated calculation a lot. Therefore, we can consider post-order traversal to define a variable flag with an initial value of true, judge the balance in the process of checking the subtree, and terminate the recursion if it is already unbalanced

Corresponding code:

class Solution {
public:
                bool flag=true;
        int TreeDepth(TreeNode*root){
             if(!root||!flag)return 0;//!flag是为了终止递归返回什么都不重要
                    int leftDepth=TreeDepth(root->left);//求左子树的高度
                    int rightDepth=TreeDepth(root->right);//求右子树的高度
                    if(abs(leftDepth-rightDepth)>1){//不平衡
                        flag=false;
                    }
                    return max(leftDepth,rightDepth)+1;

          }
    bool isBalanced(TreeNode* root) {
             TreeDepth(root);
             return flag;
    }
};

Or this is also possible:

class Solution {
public:
           bool _isBalanced(TreeNode*root,int&ph){
                if(!root){
                    ph=0;
                    return true;
                }
                int leftHight=0;
                if(!_isBalanced(root->left,leftHight))return false;
                  int rightHight=0;
                if(!_isBalanced(root->right,rightHight))return false;
                ph=max(leftHight,rightHight)+1;
                return abs(leftHight-rightHight)<2;
            }
    bool isBalanced(TreeNode* root) {
                int _hight=0;
            return _isBalanced(root,_hight);
    }
};

Determine if a tree is full binary tree

Ideas:

Put all the nodes of the tree into the queue,

and then control the nodes to be dequeued according to the number of nodes in each layer of the full binary tree. If each layer satisfies the control of the number of nodes, it is a full binary tree.

As long as there is a layer that does not meet the number of dequeues, it is not a full binary tree.
 

Corresponding code:

bool isFullTree(TreeNode*root){
	if(!root)return false;//空树不是完全二叉树
	int num=1;//第一层一个节点
	queue<TreeNode*>q;
	q.push(root);
	while(!q.empty()){
		int i;
		for( i=0;i<num&&!q.empty();i++){
              while(!q.empty()){
				  auto node=q.top();
				  q.pop();
				  if(node->left){
					  q.push(node->left);
				  }
				  if(node->right){
					  q.push(node->right);
				  }
			  }
		}//只要有一层出队的个数小于num那么他就不是满二叉树
		if(i<num){
			return false;
		}
		else{
			num*=2;
		}
	}
	return true;
}

The code and problem-solving ideas corresponding to the complete binary tree can be found in my basics of binary tree.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324136667&siteId=291194637