Binary Tree Inorder Traversal @leetcode

本文介绍了一种使用栈实现二叉树中序遍历的方法,并附带了详细的代码示例。通过巧妙地利用辅助节点和标记来跟踪遍历状态,此方法有效地解决了中序遍历的问题。

http://oj.leetcode.com/problems/binary-tree-inorder-traversal/

 1 vector<int> inorderTraversal(TreeNode *root) {
 2         stack<TreeNode *> nextstep;
 3         vector<int> res;
 4         TreeNode *p=root;
 5         TreeNode *DIRTY = new TreeNode(0);
 6         bool isMid = true;
 7         while(p){
 8             if(p->right && isMid) {nextstep.push(p->right);}
 9             
10             if(p == DIRTY){
11                 p = nextstep.top();
12                 isMid = (p == DIRTY)?false:true;
13                 nextstep.pop();
14             }
15             if(p->left && isMid){
16                 nextstep.push(p);
17                 nextstep.push(DIRTY);
18                 p = p->left;
19             }
20             else{
21                 if(p)
22                     res.push_back(p->val);
23                 if(nextstep.size()>0){
24                     p = nextstep.top();
25                     isMid = (p == DIRTY)?false:true;
26                     nextstep.pop();
27                     if(!isMid){
28                         p = nextstep.top();
29                         nextstep.pop();
30                     }
31                 }
32                 else{
33                     break;
34                 }
35             }
36         }
37         delete DIRTY;
38         return res;
39     }

=发现二叉树跟栈,队列这些数据结构的东西,真是可以完美结合。

#相信还有更好的办法,也许我下次再写这道题,就会更好。

转载于:https://www.cnblogs.com/rogarlee/p/3449946.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值