首页 > Windows开发 > 详细

二叉树前序遍历C#实现

时间:2018-04-29 14:56:11      阅读:450      评论:0      收藏:0      [点我收藏+]

 

迭代实现:

 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;
        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;
    }
}

 

二叉树前序遍历C#实现

原文:https://www.cnblogs.com/wuwan/p/8970974.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!