Leetcode 94. Binary Tree Inorder Traversal

原创 2016年08月28日 19:05:49

题意:中序遍历二叉树,要求非递归


思路:设置一个栈,给每个节点设置一个标号,代表是否展开过。若未展开过,前序遍历就按right left root ,中序遍历就按 right  root left,后序遍历就按root right left压入栈。发现展开过,就直接放入vector中。循环,至栈为空,得到的vector就是遍历后的结果



/**
 * 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> inorderTraversal(TreeNode* root) {
        vector<int> ret;
        if(root == NULL)
            return ret;
        stack <pair<TreeNode *,bool> > tree;
        //pair<TreeNode *,bool> *p;
        TreeNode *p;
        bool depose;
        
        tree.push(make_pair(root,false));
        while(!tree.empty()){
            p = tree.top().first;
            depose = tree.top().second;
            tree.pop();
            
            if(!depose){//未展开
            
                if(p->right != NULL)            //左子树
                    tree.push(make_pair(p->right,false));
                tree.push(make_pair(p,true));   //根,记为ture,表示已展开过
                if(p->left != NULL)             //右子树
                    tree.push(make_pair(p->left,false));
            }else{
                ret.push_back(p->val);
            }
            
        }
        return ret;
    }
};




相关文章推荐

LeetCode94 Binary Tree Inorder Traversal(迭代实现) Java

题目: Given a binary tree, return the inorder traversal of its nodes’ values. For example: Given bi...

LeetCode 94. Binary Tree Inorder Traversal 题解

题目链接:点击打开链接   本题为非递归实现中序遍历。Java 参考代码如下: /** * Definition for a binary tree node. * public class ...

leetcode-94-Binary Tree Inorder Traversal

#include #include #include using namespace std; //Definition for a binary tree node. struct TreeN...

leetcode 94. Binary Tree Inorder Traversal-中序遍历|递归|非递归

原题链接:94. Binary Tree Inorder Traversal 【思路-Java、Python】 非递归实现用到了栈,以[1,2,3,4,5,null,6]为例,下图模拟了这个过程 ...

LeetCode 94 Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values. For example: Given binary t...

Leetcode 94:Binary Tree Inorder Traversal (二叉树中序遍历,非递归)

94. Binary Tree Inorder Traversal 提交地址: https://leetcode.com/problems/binary-tree-inorder-traversal/...

[LeetCode]94.Binary Tree Inorder Traversal

【题目】 Given a binary tree, return the inorder traversal of its nodes' values. For example: Given b...

Leetcode[94]-Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes’ values.For example: Given binary tr...

LeetCode 94: Binary Tree Inorder Traversal

Binary Tree Inorder TraversalGiven a binary tree, return the inorder traversal of its nodes’ values....

[leetcode]94. Binary Tree Inorder Traversal@Java解题报告

https://leetcode.com/problems/binary-tree-inorder-traversal/description/ Given a ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Leetcode 94. Binary Tree Inorder Traversal
举报原因:
原因补充:

(最多只允许输入30个字)