题意:inorder 遍历。
思路:dfs。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> re;
vector<int> inorderTraversal(TreeNode* root) {
dfs(root);
return re;
}
int dfs(TreeNode* root) {
if(!root) return 0;
if(root->left) dfs(root->left);
re.push_back(root->val);
if(root->right) dfs(root->right);
return 0;
}
};

本文介绍了一种使用深度优先搜索(DFS)算法来实现二叉树的中序遍历的方法。通过递归的方式先遍历左子树,然后访问根节点,最后遍历右子树。
1189

被折叠的 条评论
为什么被折叠?



