• [LeetCode]94.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.


    【代码】

    /*********************************
    *   日期:2014-11-17
    *   作者:SJF0115
    *   题号: Binary Tree Inorder Traversal
    *   来源:https://oj.leetcode.com/problems/binary-tree-inorder-traversal/
    *   结果:AC
    *   来源:LeetCode
    *   总结:
    **********************************/
    #include <iostream>
    #include <malloc.h>
    #include <vector>
    #include <stack>
    using namespace std;
    
    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> v;
            if (root == NULL){
                return v;
            }
            // 根节点入栈
            stack<TreeNode*> stack;
            TreeNode* node = root;
            // 遍历
            while(node != NULL || !stack.empty()){
                //遍历左子树
                if(node != NULL){
                    stack.push(node);
                    node = node->left;
                }
                else{
                    //左子树为空,訪问右子树
                    node = stack.top();
                    stack.pop();
                    v.push_back(node->val);
                    node = node->right;
                }
            }
            return v;
        }
    };
    
    //按先序序列创建二叉树
    int CreateBTree(TreeNode* &T){
        char data;
        //按先序次序输入二叉树中结点的值(一个字符),‘#’表示空树
        cin>>data;
        if(data == '#'){
            T = NULL;
        }
        else{
            T = (TreeNode*)malloc(sizeof(TreeNode));
            //生成根结点
            T->val = data-'0';
            //构造左子树
            CreateBTree(T->left);
            //构造右子树
            CreateBTree(T->right);
        }
        return 0;
    }
    
    int main() {
        Solution solution;
        TreeNode* root(0);
        CreateBTree(root);
        vector<int> v = solution.inorderTraversal(root);
        for(int i = 0;i < v.size();i++){
            cout<<v[i]<<endl;
        }
    }
    



  • 相关阅读:
    hdu 2063 二分图—最大匹配
    sql 中文转拼音首字母
    PhpStorm中如何使用Xdebug工具,入门级操作方法
    Linux怎么查看软件安装路径 查看mysql安装在哪
    仿淘宝实现多行星级评价
    Syslog linux 日志 规格严格
    Windows 退出码 规格严格
    AIX 查看进程监听端口 规格严格
    AIX tar zxvf 规格严格
    IpV6 linux RedHat5 规格严格
  • 原文地址:https://www.cnblogs.com/wzjhoutai/p/7291583.html
Copyright © 2020-2023  润新知