欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

算法 - 深度优先搜索和广度优先搜索 - 深度优先 - 非递归

最编程 2024-03-24 20:39:46
...
void dfs(TreeNode *pRoot)
{
        if (!pRoot)  return;
        stack<TreeNode*> s;
        TreeNode* cur = pRoot;
        while (cur || !s.empty()) {
            while (cur) {
                s.push(cur);
                cur = cur->left;
            }
            cur = s.top();
            cout<<cur.val;
            s.pop();
            cur = cur->right;
        }
        return true;
}

推荐阅读