# 递归法

``````class Solution {

/**
* @param TreeNode \$root
* @return Boolean
*/
function isBalanced(\$root) {
return \$this->getHeight(\$root) == -1 ? false : true;
}
function getHeight(\$node){
if(\$node == null) return 0;
//左
\$leftHeight = \$this->getHeight(\$node->left);
if(\$leftHeight == -1) return -1;
//右
\$rightHeight = \$this->getHeight(\$node->right);
if(\$rightHeight == -1) return -1;

// print_r("nodeVal:" . \$node->val."\n");
// print_r("leftHeight:".\$leftHeight."\n");
// print_r("rightHeight:".\$rightHeight."\n\r");
//中
if(abs(\$rightHeight - \$leftHeight) > 1){
return -1;
}else{
//返回当前节点的高度
return 1 + max(\$leftHeight, \$rightHeight);
}
}
}``````

# 递归法

``````class Solution {
private \$res = [];
/**
* @param TreeNode \$root
* @return String[]
*/
function binaryTreePaths(\$root) {
if(\$root == null) return \$this->res;
\$route = '';
\$this->treeLoop(\$root, \$route);
return \$this->res;
}

function treeLoop(\$cur, \$route){
//要先收集路径，再判断叶子结点
\$route .= \$cur->val . "->";
if(\$cur->left == null && \$cur->right == null) {
//去除最右边的"->"符号，收获路径
\$this->res[] = rtrim(\$route,"->");
return;
}
if(\$cur->left != null){
\$this->treeLoop(\$cur->left, \$route);
}

if(\$cur->right != null){
\$this->treeLoop(\$cur->right, \$route);
}
}
}``````

# 解题方法

• node->left != NULL //节点左孩子不为空
• node->left->left == NULL //节点左孩子的左孩子为空
• node->left->right == NULL//节点左孩子的右孩子为空

# 递归法

``````class Solution {
private \$count = 0;
/**
* @param TreeNode \$root
* @return Integer
*/
function sumOfLeftLeaves(\$root) {
\$this->traversal(\$root);
return \$this->count;
}

function traversal(\$root){
if(\$root == null) return;
//判断当前节点的左孩子节点不为空，并且左孩子节点的左右节点都为空，才能判断当前节点的左孩子节点是左叶子结点
if(\$root->left != null && \$root->left->left == null && \$root->left->right == null){
\$this->count += \$root->left->val;
}
if(\$root->left) \$this->sumOfLeftLeaves(\$root->left);
if(\$root->right) \$this->sumOfLeftLeaves(\$root->right);
return;
}
}``````

# 层序遍历

``````class Solution {

/**
* @param TreeNode \$root
* @return Integer
*/
function sumOfLeftLeaves(\$root) {
\$res = 0;
if(\$root == null) return \$res;
\$queue = new SplQueue();
\$queue->enqueue(\$root);
while(!\$queue->isEmpty()){
\$count = \$queue->count();
while(\$count--){
\$node = \$queue->dequeue();
if(\$node->left != null){
//print_r(\$node->left->val);
//需要判断是否叶子节点 再做叠加
if(\$node->left->left == null && \$node->left->right == null){
\$res += \$node->left->val;
}
\$queue->enqueue(\$node->left);
}
if(\$node->right != null){
\$queue->enqueue(\$node->right);
}
}
}
return \$res;
}
}``````

《L01 基础入门》

《L04 微信小程序从零到发布》

(=￣ω￣=)··· 暂无内容！

64

33

169

334