110.平衡二叉树
给定一个二叉树,判断它是否是平衡二叉树
思路:递归单层逻辑:分别求出左右子树的高度,然后如果差值小于等于1,则返回当前二叉树的高度,否则返回-1,表示已经不是平衡二叉树
c++:
class Solution {
public:
int getheight(TreeNode* node) {
if (node == nullptr) {
return 0;
}
int leftheight = getheight(node->left);
if (leftheight == -1)
return -1;
int rightheight = getheight(node->right);
if (rightheight == -1)
return -1;
return abs(leftheight - rightheight) > 1 ? -1: 1 + max(leftheight, rightheight);
}
bool isBalanced(TreeNode* root) {
return getheight(root) == -1 ? false : true;
}
};
python:
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
return self.get_height(root) != -1
def get_height(self, node):
if not node:
return 0
left = self.get_height(node.left)
right = self.get_height(node.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return max(left, right) + 1
257. 二叉树的所有路径
给你一个二叉树的根节点 root
,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
class Solution {
private:
void traversal(TreeNode* cur, string path, vector<string>& result) {
path += to_string(cur->val); // 中
if (cur->left == nullptr && cur->right == nullptr) {
result.push_back(path);
return;
}
if (cur->left) {
path += "->";
traversal(cur->left, path, result);
path.pop_back(); // 回溯'>'
path.pop_back(); // 回溯'-'
}
if (cur->right) {
path += "->";
traversal(cur->right, path, result);
path.pop_back(); // 回溯'>'
path.pop_back(); // 回溯'-'
}
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
string path;
if (root == nullptr)
return result;
traversal(root, path, result);
return result;
}
};
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def traversal(self, cur, path,result):
path.append(cur.val)
if not cur.left and not cur.right:
spath='->'.join(map(str,path))
result.append(spath)
return
if cur.left:
self.traversal(cur.left,path,result)
path.pop()
if cur.right:
self.traversal(cur.right,path,result)
path.pop()
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
result=[]
path=[]
if not root:
return result
self.traversal(root,path,result)
return result
404.左叶子之和
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
leftvalue=0
if root.left is not None and root.left.left is None and root.left.right is None:
leftvalue=root.left.val
return leftvalue + self.sumOfLeftLeaves(root.left)+self.sumOfLeftLeaves(root.right)
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == nullptr)
return 0;
int leftvalue = 0;
if (root->left != nullptr && root->left->left == nullptr &&
root->left->right == nullptr) {
leftvalue = root->left->val;
}
return leftvalue + sumOfLeftLeaves(root->left) +
sumOfLeftLeaves(root->right);
}
};