二叉树的深度遍历和图的深度优先搜索很相似,遍历过程如下:先遍历根节点,然后从根节点的左孩子开始向下直到访问到叶子结点;当根的左子树访问完毕后,再访问右子树。如下图所示的二叉树,访问顺序为:A-B-D-E-C-F-G
C++实现(20180421更新):
/*
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x): val(x), left(NULL), right(NULL) {}
};
*/
//深度遍历DFS
vector<int> DFS(TreeNode* root)
{
vector<int> ret;
if(root)
ret.push_back(root->val);
if(root->left)
DFS(root->left);
if(root->right)
DFS(root->right);
return ret;
}