Binary Tree Inorder Traversal
来源:互联网 发布:vr与游戏美工 编辑:程序博客网 时间:2024/05/19 10:38
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?
Recursive :
/** * 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> path; inorder(root, path); return path; } void inorder(TreeNode *root, vector<int> &path){ if(root){ inorder(root->left,path); path.push_back(root->val); inorder(root->right,path); } }};
Iterative:
/** * 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> path; stack<TreeNode*> stk; while(root!=NULL || !stk.empty()){ if(root){ while(root!=NULL){ stk.push(root); root=root->left; } }else{ root=stk.top(); stk.pop(); path.push_back(root->val); root=root->right; } } return path; }};
0 0
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- ubuntu12.04下ATI双显卡安装
- hdu1207 汉诺塔II 简单dp
- 黑马程序员_第七天视频学习 类和对象的三大特性
- Java“白皮书”的关键术语
- 通过汉诺塔问题理解递归的精髓
- Binary Tree Inorder Traversal
- ubuntu 12.04下 Common-solution
- 内核模式下的文件操作
- VC/MFC开发中的句柄HWND
- apue.h包头找不到的问题
- C++Primer学习札记_标准库String类
- linux yum命令详解
- Android 设置默认Launcher
- 我的debian7.2-kde版配置过程。