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);}
};