OfferCome-0531
今天学习到了二叉树中序遍历的经典写法
搜索二叉树的很多问题都可以使用中序遍历解决:因为BST的重要性质就是:BST的中序遍历是升序数组
public List<Integer> inorderTraversal(TreeNode root){ List<Integer> ret = new ArrayList<Integer>(); if(root == null) return ret; Stack<TreeNode> stack = new Stack<TreeNode>(); while(root != null || !stack.isEmpty()){ while(root != null){ stack.push(root); root = root.left; } root = stack.pop(); ret.add(root.val);//可以根据需求对此点进行其他操作 root = root.right; } return ret; }
比如,需找BST的第k个小的元素,比如判断一个树是否为BST
详见总结:https://leetcode.com/discuss/104011/iterative-inorder-traversal-multiple-questions-solution