513.找左下角的值
给定一个二叉树的 根节点 root
,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点。
思路:广度优先搜索这棵树,先把右儿子入队,再把左儿子入队,这样最后一个出队的节点就是左下角的节点了。
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
TreeNode *node;
queue<TreeNode *> q;
q.push(root);
while(!q.empty()){
node=q.front(); // 返回队首元素的值,但不删除该元素
q.pop();//删除队列首元素但不返回其值
if(node->right) q.push(node->right);
if(node->left) q.push(node->left);
}
return node->val;
}
};
class Solution:
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
q=deque([root])
while q:
node=q.popleft()
if node.right:q.append(node.right)
if node.left: q.append(node.left)
return node.val
112.路径之和
给你二叉树的根节点 root
和一个表示目标和的整数 targetSum
。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum
。如果存在,返回 true
;否则,返回 false
。
叶子节点 是指没有子节点的节点。
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if (root == nullptr) {
return false;
}
targetSum -= root->val;
if (root->left == root->right) {
return targetSum == 0;
}
return hasPathSum(root->left, targetSum) || hasPathSum(root->right, targetSum);
}
};
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root is None:
return False
targetSum -= root.val
if root.left is root.right:
return targetSum == 0
return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum)
106.从中序遍历和后序遍历构造二叉树
给定两个整数数组 inorder
和 postorder
,其中 inorder
是二叉树的中序遍历, postorder
是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
if not postorder:
return None
left_size = inorder.index(postorder[-1])
left = self.buildTree(inorder[:left_size], postorder[:left_size])
right = self.buildTree(inorder[left_size + 1 :], postorder[left_size:-1])
return TreeNode(postorder[-1], left, right)