From f5d96222a0e01633faa967095bad56b3991044f6 Mon Sep 17 00:00:00 2001 From: ShusenTang Date: Thu, 25 Jun 2020 18:40:10 +0800 Subject: [PATCH] add code2 of iterative solution --- .../94. Binary Tree Inorder Traversal.md | 36 ++++++++++++++++--- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/solutions/94. Binary Tree Inorder Traversal.md b/solutions/94. Binary Tree Inorder Traversal.md index fc42b2f..4c43ff9 100644 --- a/solutions/94. Binary Tree Inorder Traversal.md +++ b/solutions/94. Binary Tree Inorder Traversal.md @@ -30,27 +30,53 @@ public: ``` ## 思路二 +### 写法一 ``` C++ class Solution { public: vector inorderTraversal(TreeNode* root) { vectorres; - if(!root) return res; stackstk; TreeNode* p = root; while(!stk.empty() || p){ - if(p){ + if(p){ // 左: 一路向左下降 stk.push(p); - p = p -> left; // 一路向左 + p = p -> left; } else{ - p = stk.top(); + p = stk.top(); // 中: 下降不动了, 访问栈顶元素 stk.pop(); res.push_back(p -> val); - p = p -> right; + p = p -> right; // 右: 访问右子树 } } return res; } }; ``` +### 写法二 +``` C++ +class Solution { +public: + vector inorderTraversal(TreeNode* root) { + vectorres; + stackstk; + TreeNode *p = root; + + while(!stk.empty() || p){ + // 左: 一路向左下降 + while(p){ + stk.push(p); + p = p -> left; + } + // 中: 下降不动了, 访问栈顶元素 + p = stk.top(); stk.pop(); + res.push_back(p -> val); + // 右: 访问右子树 + p = p -> right; + } + + return res; + } +}; +```