前序遍历
/**
* <a href="https://leetcode.cn/problems/binary-tree-preorder-traversal/">144. 二叉树的前序遍历</>
* <p>
* 中 左 右
*/
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
list.add(root.val);
list.addAll(preorderTraversal(root.left));
list.addAll(preorderTraversal(root.right));
return list;
}
public List<Integer> preorderTraversalByStack(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if (root == null) {
return list;
}
stack.push(root);
TreeNode pop;
while (!stack.isEmpty()) {
pop = stack.pop();
if (pop.right != null) {
stack.push(pop.right);
}
if (pop.left != null) {
stack.push(pop.left);
}
list.add(pop.val);
}
return list;
}
后序遍历
/**
* <a href="https://leetcode.cn/problems/binary-tree-postorder-traversal/">145. 二叉树的后序遍历</a>
* <p>
* 左 右 中
*/
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
list.addAll(postorderTraversal(root.left));
list.addAll(postorderTraversal(root.right));
list.add(root.val);
return list;
}
public List<Integer> postorderTraversalByStack(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if (root == null) {
return list;
}
stack.push(root);
TreeNode pop;
while (!stack.isEmpty()) {
pop = stack.pop();
if (pop.left != null) {
stack.push(pop.left);
}
if (pop.right != null) {
stack.push(pop.right);
}
list.add(pop.val);
}
Collections.reverse(list);
return list;
}
中序遍历
/**
* <a href="https://leetcode.cn/problems/binary-tree-inorder-traversal/">94. 二叉树的中序遍历</a>
* <p>
* 左 中 右
*/
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
list.addAll(inorderTraversal(root.left));
list.add(root.val);
list.addAll(inorderTraversal(root.right));
return list;
}
public List<Integer> inorderTraversalByStack(TreeNode root) {
List<Integer> list = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if (root == null) {
return list;
}
TreeNode pop = root;
while (pop != null || !stack.isEmpty()) {
if (pop != null) {
stack.push(pop);
pop = pop.left;
} else {
pop = stack.pop();
list.add(pop.val);
pop = pop.right;
}
}
return list;
}
标签:return,迭代,顺带,list,pop,二叉树,null,root,stack
From: https://www.cnblogs.com/Chain-Tian/p/16997473.html