首页 > 其他 > 详细

【leetcode】Binary Tree Inorder Traversal

时间:2015-04-08 23:21:07      阅读:270      评论:0      收藏:0      [点我收藏+]

与前面的先序遍历相似。

此题为后序遍历。

 

C++:

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> inorderTraversal(TreeNode *root) {
13         vector<int>path;
14         stack<TreeNode*>stk;
15         while(root!=NULL||!stk.empty())
16         {
17             while(root!=NULL)
18             {
19                 stk.push(root);
20                 root=root->left;
21             }
22             if(!stk.empty())
23             {
24                 root=stk.top();
25                 path.push_back(root->val);
26                 stk.pop();
27                 root=root->right;
28             }
29         }
30         return path;
31     }
32 };

 

Python:

 1 # Definition for a  binary tree node
 2 # class TreeNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution:
 9     # @param root, a tree node
10     # @return a list of integers
11     def inorderTraversal(self, root):
12         if root is None:
13             return []
14         return self.inorderTraversal(root.left)+[root.val]+self.inorderTraversal(root.right)

 

【leetcode】Binary Tree Inorder Traversal

原文:http://www.cnblogs.com/jawiezhu/p/4404550.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!