My code: The idea of using the previous one to find a path of a binary tree and a specific valueSource Code
struct TreeNode{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
#ifndef BINARY_TREE_DEEP_H
#define BINARY_TREE_DEEP_H
#include "reconstructBinaryTree.h"
#include<stack>
#include<set>
void treeDeepCore(TreeNode *node ,std::stack<TreeNode*> &v_stack,std::set<int> &v_set);
int getBinaryTreeDeep(TreeNode **root){
if(root==NULL||*root==NULL){
return 0;
}
std::stack<TreeNode*> g_stack;
std::set<int> g_set;
treeDeepCore(*root,g_stack,g_set);
std::cout<<*(g_set.begin())<<std::endl;
return *(g_set.rbegin());
}
void treeDeepCore(TreeNode *node ,std::stack<TreeNode*> &v_stack,std::set<int> &v_set){
if(node==NULL){
return;
}
v_stack.push(node);
if(node->left==NULL&&node->right==NULL){
v_set.insert(v_stack.size());
}
treeDeepCore(node->left,v_stack,v_set);
treeDeepCore(node->right,v_stack,v_set);
if(!v_stack.empty()){
v_stack.pop();
}
}
#endif
Test Code
#include"binaryTreeDeep.h"
int main(){
int pre[8]={1,2,4,7,3,5,6,8};
int mid[8]={4,7,2,1,5,3,8,6};
struct TreeNode *root=reconstructBinaryTree(pre,mid,8); //重建二叉树
std::cout<<getBinaryTreeDeep(&root);
}
For example, in order to find the depth of a tree we can actually do this, nothing but to find the length of the maximum path, with the idea of recursion can solve the problem. You see the maximum depth is the following cases: Left dial hand tree is empty, the right subtree is not empty: depth is Zuozi depth plus 1. The left subtree is not empty, the right subtree is empty: depth is the depth of the right subtree plus 1 so the subtree is not empty: the depth is the maximum depth of the two is 1.
int binaryTreeDeepCore(TreeNode *node){
if(node==NULL){
return 0;
}
int leftDeep=binaryTreeDeepCore(node->left);
int rightDeep=binaryTreeDeepCore(node->right);
return (leftDeep>rightDeep)? (leftDeep+1):(rightDeep+1);
}
On this basis to determine whether a tree is a balanced binary tree, so know, that is, to see if a tree exists two or so node depth difference greater than 1 well.Source Code
#ifndef IS_BALANCETREE_H
#define IS_BALANCETREE_H
#include"reconstructBinaryTree.h"
int binaryTreeDeepCore(TreeNode *node);
bool isBalanceBT(TreeNode *root){
if(root==NULL){
return true;
}
int leftDeep=binaryTreeDeepCore(root->left);
int rightDeep=binaryTreeDeepCore(root->right);
int diffDeep=leftDeep-rightDeep;
if(diffDeep>1||diffDeep<-1)
return false;
return binaryTreeDeepCore(root->left)&&binaryTreeDeepCore(root->right);
}
int binaryTreeDeepCore(TreeNode *node){
if(node==NULL){
return 0;
}
int leftDeep=binaryTreeDeepCore(node->left);
int rightDeep=binaryTreeDeepCore(node->right);
return (leftDeep>rightDeep)? (leftDeep+1):(rightDeep+1);
}
#endif
From for notes (Wiz)
The depth of binary tree and the judgement of two-fork balance tree