Leecode[94] 二叉树的中序遍历

2020-10-12  本文已影响0人  饭板板

题目

非递归方式实现二叉树中序遍历

代码

public class Solution {
    public IList<int> InorderTraversal(TreeNode root) {
            var res = new List<int>();
            if (root == null)
            {
                return res;
            }

            var stack = new Stack<TreeNode>();
            while (root != null || stack.Count != 0)
            {
                while (root != null)
                {
                    // 先将节点追加到栈中,再访问左节点
                    stack.Push(root);
                    root = root.left;
                }

                if (stack.Count != 0)
                {
                    var node = stack.Pop();
                    res.Add(node.val);
                    root = node.right;
                }
            }

            return res;
    }
}

错误点

上一篇 下一篇

猜你喜欢

热点阅读