LeetCode: Binary Tree Inorder Traversal

一次过

 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     void dfs(TreeNode *root, vector<int> &ret) {

13         if (!root) return;

14         dfs(root->left, ret);

15         ret.push_back(root->val);

16         dfs(root->right, ret);

17     }

18     vector<int> inorderTraversal(TreeNode *root) {

19         // Start typing your C/C++ solution below

20         // DO NOT write int main() function

21         vector<int> ret;

22         dfs(root, ret);

23         return ret;

24     }

25 };

 写了一个不需要递归的代码,这段代码更好

 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         // Start typing your C/C++ solution below

14         // DO NOT write int main() function

15         stack<TreeNode *> S;

16         vector<int> ret;

17         if (!root) return ret;

18         S.push(root);

19         while (!S.empty()) {

20             TreeNode *tmp = S.top();

21             if (tmp->left) {

22                 S.push(tmp->left);

23                 tmp->left = NULL;

24             }

25             else {

26                 ret.push_back(tmp->val);

27                 S.pop();

28                 if (tmp->right) S.push(tmp->right);

29             }

30         }

31         return ret;

32     }

33 };

 C#

 1 /**

 2  * Definition for a binary tree node.

 3  * public class TreeNode {

 4  *     public int val;

 5  *     public TreeNode left;

 6  *     public TreeNode right;

 7  *     public TreeNode(int x) { val = x; }

 8  * }

 9  */

10 public class Solution {

11     public List<int> InorderTraversal(TreeNode root) {

12         Stack<TreeNode> S = new Stack<TreeNode>();

13         List<int> ans = new List<int>();

14         if (root == null) return ans;

15         S.Push(root);

16         while(S.Count != 0)

17         {

18             TreeNode top = S.Peek();

19             if (top.left != null) {

20                 S.Push(top.left);

21                 top.left = null;

22             }

23             else {

24                 ans.Add(top.val);

25                 S.Pop();

26                 if (top.right != null) S.Push(top.right);

27             }

28         }

29         return ans;

30     }

31 }
View Code

 

你可能感兴趣的:(LeetCode)