LeetCode Online Judge 题目C# 练习 - Binary Tree Inorder Traversal

 1         public static List<int> BinaryTreeInorderTraveral(BTNode root)

 2         {

 3             List<int> ret = new List<int>();

 4             BinaryTreeInorderTraveralHelper(root, ret);

 5             return ret;

 6         }

 7 

 8         public static void BinaryTreeInorderTraveralHelper(BTNode root, List<int> ret)

 9         {

10             if (root == null)

11                 return;

12 

13             BinaryTreeInorderTraveralHelper(root.Left, ret);

14             ret.Add(root.Value);

15             BinaryTreeInorderTraveralHelper(root.Right, ret);

16         }

代码分析:

  Inorder Traveral应该没难度吧?但是如果不能用递归就稍稍有点难度了,我相信如果面试问这题,递归肯定不能让面试官满意的。

 1         public static List<int> BinaryTreeInorderTraverlOpt(BTNode root)

 2         {

 3             List<int> ret = new List<int>();

 4             if (root == null)

 5                 return ret;

 6 

 7             Stack<BTNode> stack = new Stack<BTNode>();

 8             bool backtrack = false;

 9 

10             stack.Push(root);

11 

12             while (stack.Count > 0)

13             {

14                 BTNode curr = stack.Peek();

15                 if (curr.Left != null && !backtrack)

16                 {

17                     stack.Push(curr.Left);

18                     backtrack = false;

19                     continue;

20                 }

21 

22                 ret.Add(curr.Value);

23                 stack.Pop();

24                 backtrack = true;

25 

26                 if (curr.Right != null)

27                 {

28                     stack.Push(curr.Right);

29                     backtrack = false;

30                 }

31             }

32 

33             return ret;

34         }

代码分析:

  Iterative做法,用一个 Stack 帮忙,记得要 backtrack flag 来标记当前是往下走还是往上走。往上走的时候就不能再把 curr.Left 加到 Stack 中了。

你可能感兴趣的:(LeetCode)