145. 二叉树的前序遍历-后序遍历-栈实现
Posted hequnwang10
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了145. 二叉树的前序遍历-后序遍历-栈实现相关的知识,希望对你有一定的参考价值。
144. 二叉树的前序遍历
给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
class Solution
public List<Integer> preorderTraversal(TreeNode root)
List<Integer> res = new ArrayList<Integer>();
if(root == null)
return res;
//使用栈
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty())
TreeNode node = stack.pop();
if(node == null)
continue;
res.add(node.val);
stack.push(node.right);//先将右子树进栈 后出
stack.push(node.left);
return res;
144. 二叉树的前序遍历
给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
class Solution
public List<Integer> postorderTraversal(TreeNode root)
List<Integer> res = new ArrayList<Integer>();
//使用栈
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
//前序遍历为 root -> left -> right
//后序遍历为 left -> right -> root
//修改前序遍历成为 root -> right -> left
//逆序
while(!stack.isEmpty())
TreeNode node = stack.pop();
if(node == null)
continue;
res.add(node.val);
stack.push(node.left);
stack.push(node.right);
Collections.reverse(res);
return res;
以上是关于145. 二叉树的前序遍历-后序遍历-栈实现的主要内容,如果未能解决你的问题,请参考以下文章