概述
对于二叉树的遍历,大家都知道使用递归的方式比较简单,但是现在笔试题大部分都要求使用迭代方式,考察你的逻辑思维能力。
递归
二叉树的中序遍历递归方式遍历代码如下:
class Solution {
List<Integer> result = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
inOrder(root , result);
return result;
}
public void inOrder(TreeNode root , List<Integer> result) {
if (root == null) {
return;
}
inOrder(root.left,result);
result.add(root.val);
inOrder(root.right,result);
}
}
迭代
二叉树的中序遍历迭代方式遍历代码如下:
class Solution {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stk = new Stack<>();
public List<Integer> inorderTraversal(TreeNode root) {
pushLeftBranch(root);
while (!stk.isEmpty()) {
TreeNode p = stk.pop();
result.add(p.val);
pushLeftBranch(p.right);
}
return result;
}
private void pushLeftBranch(TreeNode p) {
while (p != null) {
stk.push(p);
p = p.left;
}
}
}