二叉树前序遍历C#实现

 

递归实现:

 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 IList<int> PreorderTraversal(TreeNode root) {
12 12         List<int> result=new List<int>();
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 IList<int> PreorderTraversal(TreeNode root) {
        List<int> result=new List<int>();
        Stack stack=new Stack();
        TreeNode currentNode=root;
        
        while(currentNode!=null||stack.Count!=0)
        {
            stack.Push(currentNode);
            result.Add(currentNode.val);
            currentNode=currentNode.left;
            while(currentNode==null&&stack.Count!=0)
            {
                TreeNode parent=stack.Pop() as TreeNode;
                currentNode=parent.right;
            }
        }
        
        return result; } }

 

转载于:https://www.cnblogs.com/wuwan/p/8970974.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值