当前位置:   article > 正文

代码随想录Day14:二叉树Part1

代码随想录Day14:二叉树Part1

二叉树遍历:

1.递归遍历:

  前序: 中左右

  1. public class Solution
  2. {
  3. public IList<int> PreorderTraversal(TreeNode root)
  4. {
  5. List<int> list = new List<int>();
  6. Rever(root, list);
  7. return list;
  8. }
  9. public void Rever(TreeNode root,List<int> list)
  10. {
  11. if (root == null)
  12. return;
  13. list.Add(root.val);
  14. Rever(root.left,list);
  15. Rever(root.right, list);
  16. }
  17. }

中序:左中右

  1. public class Solution {
  2. public IList<int> InorderTraversal(TreeNode root) {
  3. List<int> list = new List<int>();
  4. midRever(root, list);
  5. return list;
  6. }
  7. public void midRever(TreeNode root, List<int> list)
  8. {
  9. if (root == null)
  10. return;
  11. midRever(root.left, list);
  12. list.Add(root.val);
  13. midRever(root.right,list);
  14. }
  15. }

后序 :左右中

  1. public class Solution {
  2. public IList<int> PostorderTraversal(TreeNode root) {
  3. List<int> list = new List<int>();
  4. lastRever(root, list);
  5. return list;
  6. }
  7. public void lastRever(TreeNode root, List<int> list)
  8. {
  9. if (root == null)
  10. return;
  11. lastRever(root.left,list);
  12. lastRever(root.right,list);
  13. list.Add(root.val);
  14. }
  15. }

2.迭代遍历 

前序:

  1. public class Solution
  2. {
  3. public IList<int> PreorderTraversal(TreeNode root)
  4. {
  5. Stack<TreeNode> stack = new Stack<TreeNode>();
  6. List<int> list = new List<int>();
  7. stack.Push(root);
  8. while (stack.Count > 0)
  9. {
  10. TreeNode node = stack.Pop();
  11. if (node!=null)
  12. {
  13. list.Add(node.val);
  14. }
  15. else
  16. {
  17. continue;
  18. }
  19. stack.Push(node.right);
  20. stack.Push(node.left);
  21. }
  22. return list;
  23. }
  24. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/577195
推荐阅读
相关标签
  

闽ICP备14008679号