标签:遍历 进阶 class 代码 public set out nbsp com
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
示例 1:
输入:root = [1,null,2,3] 输出:[1,2,3]
示例 2:
输入:root = [] 输出:[]
示例 3:
输入:root = [1] 输出:[1]
示例 4:
输入:root = [1,2] 输出:[1,2]
示例 5:
输入:root = [1,null,2] 输出:[1,2]
提示:
[0, 100] 内-100 <= Node.val <= 100
进阶:递归算法很简单,你可以通过迭代算法完成吗?
/**
 * 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) {
        var list = new List<int>();
        if (root == null) return list;
        var stack = new Stack<TreeNode>();
        stack.Push(root);
        /*栈顶二叉树出栈,输出其值,且若存在子树均入栈,右子树优先子树入栈*/
        while (stack.TryPop(out TreeNode node))
        {
            list.Add(node.val);
            if (node.right != null) stack.Push(node.right);
            if (node.left != null) stack.Push(node.left);
        }
        return list;
    }
}
标签:遍历 进阶 class 代码 public set out nbsp com
原文地址:https://www.cnblogs.com/fuxuyang/p/14242721.html