快速导航:
1 树形结构
1.1 树形结构 概念
树是一种非线性的数据结构,它是由n(n>=0)个有限结点组成一个具有层次关系的集合。把它叫做树是因为它看起来像一棵倒挂的树,也就是说它是根朝上,而叶朝下的。它具有以下的特点:
- 有一个特殊的结点,称为根结点,根结点没有前驱结点
- 除根结点外,其余结点被分成M(M > 0)个互不相交的集合T1、T2、…、Tm,其中每一个集合 Ti (1 <= i<= m) 又是一棵与树类似的子树。每棵子树的根结点有且只有一个前驱,可以有0个或多个后继
- 树是递归定义的。
- 注意:子树之间不能有交集 !
1.2 需要记忆概念
- 结点的度:一个结点含有子树的个数称为该结点的度; 如上图:A的度为6
- 树的度:一棵树中,所有结点度的最大值称为树的度; 如上图:树的度为6
- 叶子结点或终端结点:度为0的结点称为叶结点; 如上图:B、C、H、I…等节点为叶结点
- 双亲结点或父结点:若一个结点含有子结点,则这个结点称为其子结点的父结点; 如上图:A是B的父结点
- 孩子结点或子结点:一个结点含有的子树的根结点称为该结点的子结点; 如上图:B是A的孩子结点
- 根结点:一棵树中,没有双亲结点的结点;如上图:A
- 结点的层次:从根开始定义起,根为第1层,根的子结点为第2层,以此类推
- 树的高度或深度:树中结点的最大层次; 如上图:树的高度为4
不需要特殊记忆概念:
- 非终端结点或分支结点:度不为0的结点; 如上图:D、E、F、G…等节点为分支结点
- 兄弟结点:具有相同父结点的结点互称为兄弟结点; 如上图:B、C是兄弟结点
- 堂兄弟结点:双亲在同一层的结点互为堂兄弟;如上图:H、I互为兄弟结点
- 结点的祖先:从根到该结点所经分支上的所有结点;如上图:A是所有结点的祖先
- 子孙:以某结点为根的子树中任一结点都称为该结点的子孙。如上图:所有结点都是A的子孙
- 森林:由m(m>=0)棵互不相交的树组成的集合称为森林
1.3 树的表现形式
树结构相对线性表就比较复杂了,要存储表示起来就比较麻烦了,实际中树有很多种表示方式,如:双亲表示法,孩子表示法、孩子双亲表示法、孩子兄弟表示法等等。
列如 :
孩子兄弟表示法 :
class Node {
int value; // 树中存储的数据
Node firstChild; // 第一个孩子引用
Node nextBrother; // 下一个兄弟引用
}
2 二叉树
2.1 概念
一棵二叉树是结点的一个有限集合,该集合:
- 或者为空
- 或者是由一个根节点加上两棵别称为左子树和右子树的二叉树组成
从上图可以看出: - 二叉树不存在度大于2的结点
- 二叉树的子树有左右之分,次序不能颠倒,因此二叉树是有序树
注意:对于任意的二叉树都是由以下几种情况复合而成的:
2.2 两种特殊的二叉树
- 满二叉树: 一棵二叉树,如果每层的结点数都达到最大值,则这棵二叉树就是满二叉树。也就是说,如果一棵
二叉树的层数为K,且结点总数是 ,则它就是满二叉树。 - 完全二叉树: 完全二叉树是效率很高的数据结构,完全二叉树是由满二叉树而引出来的。对于深度为K的,有n
个结点的二叉树,当且仅当其每一个结点都与深度为K的满二叉树中编号从0至n-1的结点一一对应时称之为完
全二叉树。 要注意的是满二叉树是一种特殊的完全二叉树。
2.3 二叉树的性质
- 若规定根结点的层数为1,则一棵非空二叉树的第i层上最多有2^(i-1) (i>0)个结点
- 若规定只有根结点的二叉树的深度为1,则深度为K的二叉树的最大结点数是 2^k -1 (k>=0)
- 对任何一棵二叉树, 如果其叶结点个数为 n0, 度为2的非叶结点个数为 n2,则有n0=n2+1
- 具有n个结点的完全二叉树的深度k为 上取整
- 对于具有n个结点的完全二叉树,如果按照从上至下从左至右的顺序对所有节点从0开始编号,则对于序号为i的结点有:
若i>0,双亲序号:(i-1)/2;i=0,(i为根结点编号),无双亲结点
若2i+1<n,左孩子序号:2i+1,否则无左孩子
若2i+2<n,右孩子序号:2i+2,否则无右孩子
2.4 相关例题讲解
-
某二叉树共有 399 个结点,其中有 199 个度为 2 的结点,则该二叉树中的叶子结点数为(200 ) // n0=n2+1
A 不存在这样的二叉树
B 200
C 198
D 199 -
在具有 2n 个结点的完全二叉树中,叶子结点个数为( n)
A n
B n+1
C n-1
D n/2
// 2n一定是偶数,所以n1一定是1个 n0 n2不一定
所以 :(n0=n2+1) 叶子节点即为n0 解出x即可 :
相同地,对于奇数几点有 :
-
一个具有767个节点的完全二叉树,其叶子节点个数为(384)
A 383
B 384
C 385
D 386
//767是奇数,n1一定是0
n0=n2+1
有767=n0+n2=n0+n0-1====> n0(叶子节点)=384 -
一棵完全二叉树的节点数为531个,那么这棵树的高度为(10 )
A 11
B 10
C 8
D 12
//log2(n+1) 向上取整:
k=log2 534
2^9=512
531
2^10=1024
根据向上取整,得k=10
2.4 二叉树的存储
二叉树的存储结构分为:顺序存储和类似于链表的链式存储。
二叉树的链式存储是通过一个一个的节点引用起来的,常见的表示方式有二叉和三叉表示方式,具体如下:
// 孩子表示法
class Node {
int val; // 数据域
Node left; // 左孩子的引用,常常代表左孩子为根的整棵左子树
Node right; // 右孩子的引用,常常代表右孩子为根的整棵右子树
}
// 孩子双亲表示法
class Node {
int val; // 数据域
Node left; // 左孩子的引用,常常代表左孩子为根的整棵左子树
Node right; // 右孩子的引用,常常代表右孩子为根的整棵右子树
Node parent; // 当前节点的根节点
}
2.5二叉树的遍历
核心思想 : 二叉树定义是递归式的
- NLR:前序遍历(Preorder Traversal 亦称先序遍历)——访问根结点—>根的左子树—>根的右子树。
- LNR:中序遍历(Inorder Traversal)——根的左子树—>根节点—>根的右子树。
- LRN:后序遍历(Postorder Traversal)——根的左子树—>根的右子树—>根节点。
(序可以理解为根节点root)
有关二叉树三种遍历方式OJ题如下 :
2.5.1 前序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> list=new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root==null) return list;
list.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
return list;
}
}
2.5.2 中序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> list=new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root==null) return list;
inorderTraversal(root.left);
list.add(root.val);
inorderTraversal(root.right);
return list;
}
}
2.5.3 后序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> list=new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if(root==null) return list;
postorderTraversal(root.left);
postorderTraversal(root.right);
list.add(root.val);
return list;
}
}
画图举列如下:
2.5.4 层序遍历
层序遍历:除了先序遍历、中序遍历、后序遍历外,还可以对二叉树进行层序遍历。设二叉树的根节点所在层数为1,层序遍历就是从所在二叉树的根节点出发,首先访问第一层的树根节点,然后从左到右访问第2层上的节点,接着是第三层的节点,以此类推,自上而下,自左至右逐层访问树的结点的过程就是层序遍历。
2.6 相关列提讲解 :
- 某完全二叉树按层次输出(同一层从左到右)的序列为 ABCDEFGH 。该完全二叉树的前序序列为(A)
A: ABDHECFG B: ABCDEFGH C: HDBEAFCG D: HDEBFGCA
//根据题意 完全二叉树 以及层次序列 ,可以推导二叉树图形如下 :
- 二叉树的先序遍历和中序遍历如下:先序遍历:EFHIGJK;中序遍历:HFIEJKG.则二叉树根结点为(A)
A: E B: F C: G D: H
注意 : 只根据二叉树的某一个遍历,是不能完全确定一颗二叉树的
根据给出的先序遍历可以知道祖先根为E
根据中序遍历可以知道 : HFI(左子树) E(根) JKG(右子树)
最后可以推导出二叉树为:
- 设一课二叉树的中序遍历序列:badce,后序遍历序列:bdeca,则二叉树前序遍历序列为(D)
A: adbce B: decab C: debac D: abcde
方法如下
- 先遍历后序遍历的序列,从最后一个元素出发
- 最后一个是根,拿着这个元素,在中序遍历的序列中找到该根
- 根的左边是左子树,根的右边是右子树
- 接下来继续遍历后序遍历的序列,此时再次拿到的根就是这棵树的右子树
- …
根据后续遍历可以知道二叉树的祖先根为a
根据中序遍历 : b(左子树) a (祖先根) dce(右子树)
最后可以推导出二叉树为:
注意:如果给出的是前序遍历和后序遍历,是不能得到一颗确切的二叉树的,因为此时拿到的都是根,必须需要得到中序遍历,再搭配二者其一,才能确定一颗确切的二叉树 !
- 某二叉树的后序遍历序列与中序遍历序列相同,均为 ABCDEF ,则按层次输出(同一层从左到右)的序列为(A)
A: FEDCBA B: CBAFED C: DEFCBA D: ABCDEF
根据以上方法,分析题意,得到的二叉树如下:
3. 二叉树相关代码
import java.util.*;
class TreeNode {
public char val;
public TreeNode left;//左孩子的引用
public TreeNode right;//右孩子的引用
public TreeNode(char val) {
this.val = val;
}
}
public class BinaryTree {
public static int i = 0;
public TreeNode createTree(String str) {
TreeNode root = null;
if (str.charAt(i) != '#') {
root = new TreeNode(str.charAt(i));
i++;
root.left = createTree(str);
root.right = createTree(str);
} else {
i++;
}
return root;
}
public TreeNode createTree1() {
TreeNode A = new TreeNode('A');
TreeNode B = new TreeNode('B');
TreeNode C = new TreeNode('C');
TreeNode D = new TreeNode('D');
TreeNode E = new TreeNode('E');
TreeNode F = new TreeNode('F');
TreeNode G = new TreeNode('G');
TreeNode H = new TreeNode('H');
A.left = B;
A.right = C;
B.left = D;
B.right = E;
C.left = F;
C.right = G;
E.right = H;
return A;
}
/*public static int i = 0 ;
public static TreeNode createTree(String str) {
TreeNode root = null;
if(str.charAt(i) != '#') {
root = new TreeNode(str.charAt(i));
i++;
root.left = createTree(str);
root.right = createTree(str);
}else {
//遇到# 就是空树
i++;
}
return root;
}
public static void inorder(TreeNode root) {
if(root == null) {
return;
}
inorder(root.left);
System.out.print(root.val+" ");
inorder(root.right);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String str = in.nextLine();
TreeNode root = createTree(str);
inorder(root);
}
}*/
// 前序遍历
void preOrder(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.val + " ");
preOrder(root.left);
preOrder(root.right);
}
//shift+f6->回车才会生效
public List<Character> preorderTraversal(TreeNode root) {
List<Character> retlist = new ArrayList<>();
if (root == null) {
return retlist;
}
retlist.add(root.val);
List<Character> leftTree = preorderTraversal(root.left);
retlist.addAll(leftTree);
List<Character> rightTree = preorderTraversal(root.right);
retlist.addAll(rightTree);
return retlist;
}
// 中序遍历
void inOrder(TreeNode root) {
if (root == null) {
return;
}
inOrder(root.left);
System.out.print(root.val + " ");
inOrder(root.right);
}
/*public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> retlist = new ArrayList<>();
if(root == null) {
return retlist;
}
List<Integer> leftTree = inorderTraversal(root.left);
retlist.addAll(leftTree);
retlist.add(root.val);
List<Integer> rightTree =inorderTraversal(root.right);
retlist.addAll(rightTree);
return retlist;
}*/
// 后序遍历
void postOrder(TreeNode root) {
if (root == null) {
return;
}
postOrder(root.left);
postOrder(root.right);
System.out.print(root.val + " ");
}
//层序遍历
public void levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
if (root == null) {
return;
}
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
System.out.print(cur.val + " ");
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
}
}
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ret = new ArrayList<>();
if (root == null) {
return ret;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> list = new ArrayList<>();
while (size != 0) {
TreeNode cur = queue.poll();
list.add(cur.val);
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
size--;
}
ret.add(list);
}
return ret;
}
/*public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> retlist = new ArrayList<>();
if(root == null) {
return retlist;
}
List<Integer> leftTree = postorderTraversal
(root.left);
retlist.addAll(leftTree);
List<Integer> rightTree =postorderTraversal(root.right);
retlist.addAll(rightTree);
retlist.add(root.val);
return retlist;
}*/
/**
* 获取树中节点的个数
*/
int count = 0;
int size(TreeNode root) {
if (root == null) {
return 0;
}
count++;
size(root.left);
size(root.right);
return count;
}
// 子问题思路
int size1(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + size1(root.left) + size1(root.right);
}
// 获取叶子节点的个数
int countLeaf = 0;
int getLeafNodeCount(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
countLeaf++;
}
getLeafNodeCount(root.left);
getLeafNodeCount(root.right);
return countLeaf;
}
//子问题思路
int getLeafNodeCount1(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
return getLeafNodeCount1(root.left) + getLeafNodeCount1(root.right);
}
// 获取第K层节点的个数
int getKLevelNodeCount(TreeNode root, int k) {
if (root == null || k < 1) {
return 0;
}
if (k == 1) {
return 1;
}
return getKLevelNodeCount(root.left, k - 1) + getKLevelNodeCount(root.right, k - 1);
}
// 获取二叉树的高度
int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}
// 检测值为value的元素是否存在
TreeNode findVal(TreeNode root, char val) {
if (root == null) return null;
if (root.val == val) return root;
TreeNode ret = findVal(root.left, val);
if (ret != null) {
return ret;
}
ret = findVal(root.right, val);
if (ret != null) {
return ret;
}
return null;
}
/**
* 是否为完全二叉树
*
* @param root 根节点
* @return
*/
boolean isCompleteTree(TreeNode root) {
if (root == null) return true;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
if (cur != null) {
queue.offer(cur.left);
queue.offer(cur.right);
} else {
break;
}
}
while (!queue.isEmpty()) {
TreeNode top = queue.peek();
if (top != null) {
return false;
}
queue.poll();
}
return true;
}
public boolean isCompleteTreeOJ(TreeNode root) {
if (root == null) {
return true;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
if (cur == null) {
break;
}
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
}
while (!queue.isEmpty()) {
TreeNode ret = queue.poll();
if (ret != null) {
return false;
}
}
return true;
}
TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null) {
return root2;
}
if (root2 == null) {
return root1;
}
// root1.val=root1.val+root2.val;
root1.left = mergeTrees(root1.left, root2.left);
root1.right = mergeTrees(root1.right, root2.right);
return root1;
}
private boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q != null || p != null && q == null) {
return false;
}
if (p == null && q == null) {
return true;
}
if (p.val != q.val) {
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if (root == null || subRoot == null) {
return false;
}
if (isSameTree(root, subRoot)) {
return true;
}
if (isSameTree(root.left, subRoot)) {
return true;
}
if (isSameTree(root.right, subRoot)) {
return true;
}
return false;
}
public boolean isSymmetricChild(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null || left.val != right.val) {
return false;
}
return isSymmetricChild(left.left, right.right) && isSymmetricChild(left.right, right.left);
}
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return isSymmetricChild(root.left, root.right);
}
// 解法1:根据二叉搜索树的思路
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//LCA问题
if (root == null) {
return root;
}
if (root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) {
return root;
} else if (left != null) {
return left;
} else if (right != null) {
return right;
}
return null;
}
// 解法二 根据栈 路径思路
/**
* 把root到node的路径放到栈里面
*
* @param root 根节点
* @param node 需要找的节点
* @param stack 存放路径的栈
* @return
*/
public boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
if (root == null || node == null) {
return false;
}
stack.push(root);
if (root == node) {
return true;
}
boolean flg = getPath(root.left, node, stack);
if (flg == true) {
return true;
}
flg = getPath(root.right, node, stack);
if (flg == true) {
return true;
}
stack.pop();
return false;
}
public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
getPath(root, p, stack1);
getPath(root, q, stack2);
int size1 = stack1.size();
int size2 = stack2.size();
if (size1 > size2) {
int size = size1 - size2;
while (size != 0) {
stack1.pop();
size--;
}
while (!stack1.empty() && !stack2.empty()) {
if (stack1.pop() == stack2.pop()) {
return stack1.pop();
} else {
stack1.pop();
stack2.pop();
}
}
}
if (size2 > size1) {
int size = size2 - size1;
while (size != 0) {
stack2.pop();
size--;
}
while (!stack1.empty() && !stack2.empty()) {
if (stack1.pop() == stack2.pop()) {
return stack1.pop();
} else {
stack1.pop();
stack2.pop();
}
}
}
return null;
}
// 二叉搜素树转换为排好序的双向链表
/*TreeNode prev=null;
public void inorder(TreeNode pCur){
if (pCur==null){
return;
}
inorder(pCur.left);
pCur.left=prev;
if (prev!=null){
prev.right=pCur;
}
prev=pCur;
inorder(pCur.right);
}
public TreeNode Convert(TreeNode pRootOfTree) {
if (pRootOfTree==null){
return null ;
}
inorder(pRootOfTree);
while (pRootOfTree.left!=null){
pRootOfTree=pRootOfTree.left;
}
return pRootOfTree;
}*/
TreeNode prev = null;
public void inorderOJ(TreeNode root) {
if (root == null) {
return;
}
inorderOJ(root.left);
root.left = prev;
if (prev != null) {
prev.right = root;
}
prev = root;
inorderOJ(root.right);
}
public TreeNode Convert(TreeNode root) {
if (root == null) {
return null;
}
while (root.left != null) {
root = root.left;
}
return root;
}
//根据前序遍历和中序遍历来创建二叉树
public int preIndex = 0;
public TreeNode createTreeByPandI(int[] preorder, int[] inorder, int inbegin, int inend) {
if (inbegin > inend) {
return null;
}
TreeNode root = new TreeNode(preorder[preIndex]);
int rootIndex = findIndexOfI(inorder, inbegin, inend, preorder[preIndex]);
if (rootIndex == -1) {
return null;
}
preIndex++;
root.left = createTreeByPandI(preorder, inorder, inbegin, rootIndex - 1);
root.right = createTreeByPandI(preorder, inorder, rootIndex + 1, inend);
return root;
}
private int findIndexOfI(int[] inoder, int inbegin, int inend, int key) {
for (int j = inbegin; j <= inend; j++) {
if (inoder[j] == key) {
return j;
}
}
return -1;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder == null || inorder == null) {
return null;
}
return createTreeByPandI(preorder, inorder, 0, inorder.length - 1);
}
//根据后序遍历和中序遍历来创建二叉树
public int postIndex = 0;
public TreeNode createTreeByPandI(int[] inorder, int[] postorder, int inbegin, int inend) {
if (inbegin > inend) {
return null;
}
TreeNode root = new TreeNode(postorder[postIndex]);
int rootIndex = findIndexOfI(inorder, inbegin, inend, postorder[postIndex]);
if (rootIndex == -1) {
return null;
}
preIndex--;
root.right = createTreeByPandI(inorder, postorder, rootIndex + 1, inend);
root.left = createTreeByPandI(inorder, postorder, inbegin, rootIndex - 1);
return root;
}
private int findIndexOfI(int[] inoder, int inbegin, int inend, int key) {
for (int j = inbegin; j <= inend; j++) {
if (inoder[j] == key) {
return j;
}
}
return -1;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (postorder == null || inorder == null) {
return null;
}
postIndex = postorder.length - 1;
return createTreeByPandI(inorder, postorder, 0, inorder.length - 1);
}
// 二叉树创建字符串.
public void trerToString(TreeNode root, StringBuilder sb) {
if (root == null) {
return;
}
sb.append(root.val);
if (root.left != null) {
sb.append("(");
trerToString(root.left, sb);
sb.append(")");
} else {
if (root.right == null) {
return;
} else {
sb.append("()");
}
}
if (root.right == null) {
return;
} else {
sb.append("(");
trerToString(root.right, sb);
sb.append(")");
}
}
public String tree2str(TreeNode root) {
if (root == null) {
return null;
}
StringBuilder sb = new StringBuilder();
trerToString(root, sb);
return sb.toString();
}
public TreeNode increasingBST(TreeNode root) {
if (root == null) {
return null;
}
List<Integer> list = new ArrayList<>();
inorderBST(root, list);
TreeNode prevNode = new TreeNode(-1);
TreeNode rightNode = prevNode;
for (int val : list) {
rightNode.right = new TreeNode(val);
rightNode = rightNode.right;
}
return prevNode.right;
}
public void inorderBST(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
inorderBST(root.left, list);
list.add(root.val);
inorderBST(root.right, list);
}
//前序遍历非递归实现
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.empty()) {
while (cur != null) {
stack.push(cur);
ret.add(cur.val);
cur = cur.left;
}
TreeNode top = stack.pop();
cur = top.right;
}
return ret;
}
//中序遍历非递归实现
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.empty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
TreeNode top = stack.pop();
ret.add(top.val);
cur = top.right;
}
return ret;
}
//后续遍历非递归实现
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
TreeNode prev=null;
while (cur != null || !stack.empty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
TreeNode top = stack.peek();
if (top.right == null || top.right==prev) { //如果当前节点的右子树被打印过了,直接就可以弹出了
stack.pop();
ret.add(top.val);
prev=top; //记录一下 最后一次打印的节点
} else {
cur = top.right;
}
}
return ret;
}
}
- over ~ 🎈