zoukankan      html  css  js  c++  java
  • Binary Tree Inorder Traversal

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

    Example:

    Input: [1,null,2,3]
       1
        
         2
        /
       3
    
    Output: [1,3,2]

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


    typedef char ElemType; typedef struct BiTreeNode { ElemType data; struct BiTreeNode *left; struct BiTreeNode *right; }BiTreeNode,*BiTree;
    Binary Tree Inorder Traversal
    void InOrderBiTree(BiTree T){
        if(T == NULL)
            return;
            
       InOrderBiTree(T->left);
       printf("%c",T->data);
       InOrderBiTree(T->right);
    }

    以下方法可作参考,优先学习以下两种解法:
    //recursion
    C++ Solution1:
    class Solution{
        public:
            vector<int> inorderTraversal(TreeNode *root){
                vector<int> res;
                inorder(root,res);
                return res;
            }
        
        void inorder(TreeNode *root, vector<int> &res){
            if(!root) return;
            if(root->left) inorder(root->left,res);
            res.push_back(root->val);
            if(root->right) inorder(root->right,res);
        }
    };
    
    //no recursion:
    class Solution{
        public:
            vector<int> inorderTraversal(TreeNode *root){
                vector<int> res;
                stack<TreeNode*> s;
                TreeNode *p = root;
                while(!s.empty() || p){
                    if(p){
                        s.push(p);
                        p = p->left;
                    }
                    else{
                        TreeNode *t = s.top();s.pop();
                        res.push_back(t->val);
                        p = t->right;   
                    }
                }
                return res;
            }
    };
    
    
    
     
    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    在controller间分享数据(第一种办法)
    AngularJS之Factory vs Service vs Provider
    directive和controller如何通信
    AngularJS 之Services讲解
    AngularJS心得体会
    int 和Integer
    2019天梯赛练习题(L2专项练习)
    2019天梯赛练习题(L1专项练习)
    Hash冲突的几种解决方法
    HashMap
  • 原文地址:https://www.cnblogs.com/hujianglang/p/11421189.html
Copyright © 2011-2022 走看看