标签:
与前面的先序遍历相似。
此题为后序遍历。
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