101. 对称二叉树 - 力扣(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:bool dfs(TreeNode *l, TreeNode *r) {if (l == nullptr && r == nullptr) return true;if ((l == nullptr && r) || (l && r == nullptr)) return false;return (l->val == r->val) && dfs(l->left, r->right) && dfs(l->right, r->left);}bool isSymmetric(TreeNode* root) {return dfs(root->left, root->right);}
};
230. 二叉搜索树中第K小的元素 - 力扣(LeetCode)
利用二叉搜索树的中序遍历,得到的序列是有序的这一性质
当中序遍历到第k个数时,将其返回即可
/*** 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:int ans = 0;void dfs(TreeNode *cur, int k, int &i) {if (cur == nullptr) return;dfs(cur->left, k, i);i ++ ;if (i == k) {ans = cur->val;return;}dfs(cur->right, k, i);}int kthSmallest(TreeNode* root, int k) {int i = 0;dfs(root, k, i);return ans;}
};