本文主要是介绍每日两题 / 226. 翻转二叉树 98. 验证二叉搜索树(LeetCode热题100),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
226. 翻转二叉树 - 力扣(LeetCode)
以后续遍历的方式交换当前节点的左右指针
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:void dfs(TreeNode *cur){if (cur == nullptr) return;dfs(cur->left);dfs(cur->right);swap(cur->left, cur->right);}TreeNode* invertTree(TreeNode* root) {dfs(root);return root;}
};
98. 验证二叉搜索树 - 力扣(LeetCode)
中序遍历得到的序列有序
或者当实现函数dfs(TreeNode *cur, long long l, long long r)
保证当前节点的值在[l, r]区间内即可,每次dfs都需要用当前节点的值更新区间
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:bool dfs(TreeNode *cur, long long l, long long r) {if (cur == nullptr) return true;if (cur->val >= r || cur->val <= l) return false;return dfs(cur->left, l, cur->val) && dfs(cur->right, cur->val, r);}bool isValidBST(TreeNode* root) {return dfs(root, LONG_MIN, LONG_MAX);}
};
这篇关于每日两题 / 226. 翻转二叉树 98. 验证二叉搜索树(LeetCode热题100)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!