[leetcode] 94. Binary Tree Inorder Traversal

网友投稿 982 2022-08-23

[leetcode] 94. Binary Tree Inorder Traversal

Description

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

Example:

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

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

分析

递归的方法很简单,注意终止条件就行了。非递归版本需要用到栈来模拟,先要遍历到树的最左边,用栈记录回溯的路径,对每一个出栈的元素,检测其右分支,把右分支的左节点压入栈中,把出栈的值押入结果集合中,因为出栈的顺序就是中序遍历的顺序。如果读者是在不明白,还是老样子,手工对着代码模拟一下啦

代码-递归版

/** * 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 inorderTraversal(TreeNode* root) { vector res; inorder(root,res); return res; } void inorder(TreeNode* root,vector &res){ if(!root){ return; } inorder(root->left,res); res.push_back(root->val); inorder(root->right,res); }};

代码-非递归版

/** * 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 inorderTraversal(TreeNode *root) { vector result; if(root==NULL){ return result; } stack s1; TreeNode *temp=root; while(!s1.empty()||temp!=NULL){ while(temp){ s1.push(temp); temp=temp->left; } if(!s1.empty()){ temp=s1.top(); s1.pop(); result.push_back(temp->val); temp=temp->right; } } return result; }};

参考文献

​​[编程题]binary-tree-inorder-traversal​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java调优经验谈(java代码优化技巧)
下一篇:[leetcode] 173. Binary Search Tree Iterator
相关文章

 发表评论

暂时没有评论,来抢沙发吧~