二叉树的常见算法
-
二叉树的前序遍历
-
描述:(1)访问根节点;(2)递归遍历左子树;(3)递归遍历右子树;
-
题解:
//递归前序遍历 import java.util.ArrayList; public void preTraversal(Node node){ ArrayList<Node> res=new ArrayList<>(); if(node!=null) { res.add(node); preTraversal(node.left); preTraversal(node.right); } }
//非递归前序遍历 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res=new ArrayList<>(); TreeNode cur=root; Stack<TreeNode> stack=new Stack<>(); if(root==null) { return res; } stack.push(root); while(!stack.isEmpty()) { TreeNode top=stack.peek(); stack.pop(); res.add(top.val); if(top.right!=null) { stack.push(top.right); } if(top.left!=null) { stack.push(top.left); } } return res; } }
-
-
二叉树的中序遍历
-
描述:(1)递归遍历左子树;(2)访问根节点;(3)递归遍历右子树;
-
题解:
//递归中序遍历 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res=new ArrayList<>(); helper(root,res); return res; } public void helper(TreeNode root,List<Integer> res){ if(root!=null) { helper(root.left,res); res.add(root.val); helper(root.right,res); } } }
//非递归的中序遍历 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> inorderTraversal(TreeNode root) { List&l
-