【leetcode 中序遍历】Binary Tree Inorder Traversal

来源:互联网 发布:借钱软件哪个能借到钱 编辑:程序博客网 时间:2024/06/05 11:21

【leetcode 先序遍历】Binary Tree Preorder Traversal

【leetcode 后序遍历】Binary Tree Postorder Traversal

1、题目

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?


2、分析

二叉树中序遍历,按“左根右”顺序遍历结点,有递归法和迭代法。

递归法,代码简洁,但是效率低。

迭代法步骤:
(不断地push左孩子,直到没有左孩子,此时栈顶为当前子树的根,pop出来保存,再用同样的方法处理该根的右子树)
 1、p指向root
 2、将p入栈,p更新为p->left
 3、重复2,直到p为空
 4、弹出栈顶,将其val push_back到结果中,p更新为该栈顶的右孩子
 5、重复2~4
下图为例子演示:


3、代码

#递归法

<span style="font-size:18px;">/** * 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) {        vector<int> result,left_vec,right_vec;          if(!root) return result;                     //检查树是否为空                  left_vec=inorderTraversal(root->left);      //对左子树递归调用inorderTraversal()          right_vec=inorderTraversal(root->right);    //对右子树..          for(auto iter=left_vec.begin();iter!=left_vec.end();iter++)               result.push_back(*iter);          result.push_back(root->val);          for(auto i=right_vec.begin();i!=right_vec.end();i++)               result.push_back(*i);          return result;      }};</span>


#迭代法

<span style="font-size:18px;">class Solution {public:    vector<int> inorderTraversal(TreeNode *root) {      vector<int> result;      stack<TreeNode *> stk;      TreeNode *p=root;      while(p!=nullptr || !stk.empty() )      {          if(p!=nullptr)          {              stk.push(p);              p=p->left;          }          else          {              p=stk.top();              stk.pop();              result.push_back(p->val);              p=p->right;          }      }      return result;    }};</span>


0 0