Leetcode 94: Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
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 IList<int> InorderTraversal(TreeNode root) { 12 var result = new List<int>(); 13 if (root == null) return result; 14 15 var stack = new Stack<TreeNode>(); 16 stack.Push(root); 17 18 while (stack.Count > 0) 19 { 20 var p = stack.Peek(); 21 if (p.left != null) 22 { 23 stack.Push(p.left); 24 p.left = null; 25 } 26 else 27 { 28 stack.Pop(); 29 result.Add(p.val); 30 if (p.right != null) 31 { 32 stack.Push(p.right); 33 p.right = null; 34 } 35 } 36 } 37 38 return result; 39 } 40 41 public IList<int> InorderTraversalRecursive(TreeNode root) { 42 var result = new List<int>(); 43 DFS(root, result); 44 return result; 45 } 46 47 private void DFS(TreeNode node, IList<int> result) 48 { 49 if (node == null) return; 50 51 DFS(node.left, result); 52 result.Add(node.val); 53 DFS(node.right, result); 54 } 55 }

浙公网安备 33010602011771号