二叉树前序遍历C#实现
2021-04-14 02:25
标签:col roo binary nod node ret 二叉树 ini list 迭代实现: 遍历实现: 二叉树前序遍历C#实现 标签:col roo binary nod node ret 二叉树 ini list 原文地址:https://www.cnblogs.com/wuwan/p/8970974.html 1 1 /**
2 2 * Definition for a binary tree node.
3 3 * public class TreeNode {
4 4 * public int val;
5 5 * public TreeNode left;
6 6 * public TreeNode right;
7 7 * public TreeNode(int x) { val = x; }
8 8 * }
9 9 */
10 10 public class Solution {
11 11 public IListint> PreorderTraversal(TreeNode root) {
12 12 Listint> result=new Listint>();
13 13 if (root==null)
14 14 return result;
15 15 result.Add(root.val);
16 16 if(root.left!=null)
17 17 result.AddRange(PreorderTraversal(root.left));
18 18 if(root.right!=null)
19 19 result.AddRange(PreorderTraversal(root.right));
20 20 return result;
21 21 }
22 22 }
23
24
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public IListint> PreorderTraversal(TreeNode root) {
Listint> result=new Listint>();
Stack stack=new Stack();
TreeNode currentNode=root;
stack.Push(currentNode);
while(currentNode!=null)
{
result.Add(currentNode.val);
currentNode=currentNode.left;
while(currentNode==null&&stack.Count!=0)
{
TreeNode parent=stack.Pop() as TreeNode;
currentNode=parent.right;
}
}
return result;
}
}