思路:求高度用后续遍历,深度用后续遍历,
平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int getDeth(struct TreeNode* root){
if(!root)
return 0;
int left = getDeth(root->left);
int right = getDeth(root->right);
return left > right ? left + 1 : right + 1;
}
bool isBalanced(struct TreeNode* root) {
if(!root)
return 1;
int left = getDeth(root->left);
int right = getDeth(root->right);
int diff = left - right;
if(diff > 1 || diff < -1){
return 0;
}
return isBalanced(root->left) && isBalanced(root->right);
}
这段代码中是先根结点开始向下验证是否为平衡二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
void construct_path(struct TreeNode* root, char** paths, int* returnSize,int* sta, int top){
if(root){
if(!(root->left) && !(root->right)){
char* temp = (char*)malloc(1001);
int len = 0;
for(int i = 0; i < top; i++){
len += sprintf(temp + len,"%d->", sta[i]);
}
sprintf(temp + len,"%d", root->val);
paths[(*returnSize)++] = temp;
}else
{
sta[top++] = root->val;
construct_path(root->left, paths, returnSize , sta, top);
construct_path(root->right, paths, returnSize, sta, top);
}
}
}
char** binaryTreePaths(struct TreeNode* root, int* returnSize) {
char** paths = (char**)malloc(sizeof(char*)*1001);
*returnSize = 0;
int sta[1001];
construct_path(root, paths, returnSize, sta, 0);
return paths;
}
为什么要用到回溯和后续遍历
——一开始没有认真看题目,题目的要求是从根结点到根的所有路径, 所以我们遍历到最后面就要开始返回了
——用后续遍历的原因其实是单层遍历如何写,这道题目中我们是,先处理了左结点,然后到右结点,最后才到父节点的
停止条件是
——当前遍历的子结点左右指针都是空的
这里面还用了栈
——因为栈是先进后出的原因,保证了路线不会错乱
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int sumOfLeftLeaves(struct TreeNode* root){
if(!root)
return 0;
if(!(root->left) && !(root->right))
return 0;
int leftValue = sumOfLeftLeaves(root->left);
if(root->left && !(root->left->left) && !(root->left->right))
leftValue += root->left->val;
int rightValue = sumOfLeftLeaves(root->right);
int returnvalue = leftValue + rightValue;
return returnvalue;
}
为什么判断父结点的情况,而不是子结点的情况,因为遍历到子结点的的时候,不知道遍历到的是左结点还是右结点,所以就要用到判断条件就是父结点的左结点的左右结点为空的时候。