• Binary Tree Inorder Traversal


    Given a binary tree, return the inorder traversal of its nodes' values.

    For example:
    Given binary tree {1,#,2,3},

       1
        
         2
        /
       3
    

    return [1,3,2].

    Note: Recursive solution is trivial, could you do it iteratively?

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


    OJ's Binary Tree Serialization:

    The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

    Here's an example:

       1
      / 
     2   3
        /
       4
        
         5
    
    The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

    分析:这道题用递归方法很好做,但是此题却提示用循环方法解决。首先我用递归方法,把层次遍历转化为中序遍历,看代码实现就会明白:

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void traversal(TreeNode* root,vector<int> &data)
        {
            if(root==NULL)
                return;
            traversal(root->left,data);
            data.push_back(root->val);
            traversal(root->right,data);
        }
        vector<int> inorderTraversal(TreeNode *root) {
            vector<int> data;
            traversal(root,data);
            return data;
        }
    };

    循环实现,这题就有点难度了,不过没关系,我们可以借用栈空间来解决这题。树中某结点不为空,则将其左结点压入栈中,如果没有,则弹出该节点,将该节点的值存入vector中,再压入出栈元素的右结点,依次进行循环遍历,直到栈为空为止。

    /**
     * Definition for binary tree
     * 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) {
            stack<TreeNode*> StackTree;
            vector<int> data;
            if(root==NULL)
                return data;
            TreeNode *CurrentNode=root;
            while(!StackTree.empty()||CurrentNode)
            {
                if(CurrentNode!=NULL)
                {
                    StackTree.push(CurrentNode);
                    CurrentNode=CurrentNode->left;
                }
                else
                {
                    CurrentNode=StackTree.top();
                    StackTree.pop();
                    data.push_back(CurrentNode->val);
                    CurrentNode=CurrentNode->right;
                }
            }
            return data;
        }
    };
  • 相关阅读:
    几道算法题及学java心得
    css入门
    关于 移动端整屏切换专题 效果的思考
    css3实现卡牌旋转与物体发光效果
    九方格抽奖插件
    绑定弹窗事件最好的方法,原生JS和JQuery方法
    整屏滚动效果 jquery.fullPage.js插件+CSS3实现
    自定义 页面滚动条
    有趣的HTML5 CSS3效果
    CSS3 过渡与动画
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3583501.html
Copyright © 2020-2023  润新知