赞
踩
题目理解:
流程:
bool DFS(Node* root)
bool left = DFS(root->left
bool right = DFS(root->right)
root->left == nullptr -> return root
bool EvaluateTree(TreeNode* root)
{
// 函数出口
if(root->left == nullptr)
{
return root->val;
}
auto left = evaluateTree(root->left);
auto right = evaluateTree(root->right);
return root->val == 2 ? left | right : left & right;
}
int DFS(TreeNode* root, int prevNum)
prevNum
:父节点的数字class Solution { public: int sumNumbers(TreeNode* root) { return DFS(root, 0); } int DFS(TreeNode* root, int prevSum) { if(root == nullptr) { return 0; } prevSum = prevSum * 10 + root->val; if(root->left == nullptr && root->right == nullptr) { return prevSum; } return DFS(root->left, prevSum) + DFS(root->right, prevSum); } };
Node* DFS(Node* root)
root == nullptr
TreeNode* PruneTree(TreeNode* root) { if(root == nullptr) { return nullptr; } root->left = pruneTree(root->left); root->right = pruneTree(root->right); if(!root->val && !root->left && !root->right) { delete root; // 防止内存泄漏 root = nullptr; } return root; }
// v1.0 暴力判断 class Solution { long prev = LONG_MIN; public: bool isValidBST(TreeNode* root) { if(root == nullptr) { return true; } // 判断左子树 bool left = isValidBST(root->left); // 判断自己 bool cur = false; if(root->val > prev) { cur = true; } prev = root->val; // 判断右子树 bool right = isValidBST(root->right); return left && right && cur; } }; ------------------------------------------------------------------------ // v2.0 剪枝 class Solution { long prev = LONG_MIN; public: bool isValidBST(TreeNode* root) { if(root == nullptr) { return true; } // 1.判断左子树 bool left = isValidBST(root->left); if(!left) // 剪枝 { return false; } // 2.判断自己 bool cur = false; if(root->val > prev) { cur = true; } prev = root->val; if(!cur) // 剪枝 { return false; } // 3.判断右子树 bool right = isValidBST(root->right); return left && right && cur; } };
count
,将其初始化为k
,每遍历⼀个节点就将count--
,直到某次递归的时候,count == 0
,说明此时的结点就是要找的结果ret
,用于存储最终结果,简化返回值设计class Solution { int count, ret; public: int kthSmallest(TreeNode* root, int k) { count = k; DFS(root); return ret; } void DFS(TreeNode* root) { // 函数出口 + 剪枝 if(root == nullptr || count == 0) { return; } DFS(root->left); if(--count == 0) { ret = root->val; } DFS(root->right); } };
void DFS(Node* root, string path)
if(root != nullptr)
,就将当前节点的值加⼊路径path
中,否则直接返回ret
中"->"
作为路径的分隔符,继续递归遍历当前节点的左右⼦节点if(root == nullptr) return;
class Solution { vector<string> ret; public: vector<string> binaryTreePaths(TreeNode* root) { DFS(root, ""); return ret; } // 参数path实现回溯 void DFS(TreeNode* root, string path) { path += to_string(root->val); // 叶子结点 + 函数出口 if(!root->left && !root->right) { ret.push_back(path); } path += "->"; // 非叶子结点 + 剪枝 if(root->left) { DFS(root->left, path); } if(root->right) { DFS(root->right, path); } } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。