二叉树算法

/**
 * 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;
 *     }
 * }
 */

目录

二叉树镜像

求一个二叉树的高度

求一颗二叉树的总结点个数

求一颗二叉树叶子节点总数

一颗二叉树第K层的节点数

层序遍历二叉树

判断一个整数数组是否为一个二叉搜索树的后序遍历序列,数组无重复元素。

判断一个二叉树是否为平衡二叉树

求二叉树中序遍历的下一个节点

给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。

二叉树的中序遍历


​​​​​​​

二叉树镜像

先交换根节点的左右孩子,再对其左右孩子镜像

//递归实现
public class Solution {
    public void Mirror(TreeNode root) {
        if(root == null){
            return;
        }
        if(root.left == null && root.right == null){
            return;
        }
        
        //交换
        TreeNode tmpNode = root.left;
        root.left = root.right;
        root.right = tmpNode;
        
        Mirror(root.left);
        Mirror(root.right);            
    }
}



public TreeNode mirrorTree(TreeNode root) {
    if(root == null){
        return null;
    }
    TreeNode tmp = root.left;
    root.left = mirrorTree(root.right);
    root.right = mirrorTree(tmp);
    return root;
}

求一个二叉树的高度

子问题的方法

//递归实现
public class Hight {
	public int getHight(TreeNode pRoot) {
		if (pRoot == null) {
			return 0;
		}

		int left = getHight(pRoot.left);
		int right = getHight(pRoot.right);

		return left > right ? left + 1 : right + 1;
	}
}


public int maxDepth(TreeNode root) {
    if(root == null) return 0;
    return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}

求一颗二叉树的总结点个数

//递归
public class Size {
	public int getSize(TreeNode pRoot) {
		if (pRoot == null) {
			return 0;
		}
		return getSize(pRoot.left) + getSize(pRoot.right) + 1;
	}
}

求一颗二叉树叶子节点总数

//递归实现
public class LeafSize {
	public int getLeafSize(TreeNode pRoot) {
		if (pRoot == null) {
			return 0;
		}

		if (pRoot.left == null && pRoot.right == null) {
			return 1;
		}

		return getLeafSize(pRoot.left) + getLeafSize(pRoot.right);
	}
}

一颗二叉树第K层的节点数

public class KlevelSize {
	public int getKLevelSize(TreeNode pRoot, int k) {
		if (k < 1 || pRoot == null) {
			return 0;
		}

		// 根所在的一层是一个结点
		if (k == 1) {
			return 1;
		}

		return getKLevelSize(pRoot.left, k - 1) + getKLevelSize(pRoot.right, k - 1);
	}
}

层序遍历二叉树

利用Java JDK提供的Queue类实现

public class LevelOrder {
	public void print(TreeNode pRoot) {
		if (pRoot == null) {
			return;
		}

		Queue<TreeNode> queue = new LinkedList<>();
		// Queue的唯一实现它的子类LinkedList类
		queue.offer(pRoot);// 入队列
		TreeNode head = null;
		while (!queue.isEmpty()) {
			head = queue.peek();// 返回对首元素
			queue.poll();// 出队列
			System.out.print(head.val + " ");
			if (head.left != null) {
				queue.offer(head.left);
			}
			if (head.right != null) {
				queue.offer(head.right);
			}
		}
	}
}

判断一个整数数组是否为一个二叉搜索树的后序遍历序列,数组无重复元素。

public class Solution {
	public boolean VerifySquenceOfBST(int [] sequence) {
            if(sequence.length == 0){
                return false;
            }
        
            return judge(sequence, 0, sequence.length - 1);
        }
    
        private boolean judge(int [] sequence, int start, int end){
            if(start >= end){//表示以判断完毕
                return true;
            }
        
            //找到左右子树分界点
            int i = start;
            for(; i < end; i++){//end为根
                if(sequence[i] > sequence[end]){
                    break;
                }
            }
            //从右子树第一个下标开始遍历判断
            for(int j = i; j < end; j++){
                if(sequence[j] < sequence[end]){
                    return false;
                }
            }
        
            return judge(sequence, start, i-1) && judge(sequence, i, end - 1);
        }
}

判断一个二叉树是否为平衡二叉树

public class BalanceTree {
	boolean flag = true;
        public boolean IsBalanced_Solution(TreeNode root) {
            getHight(root);
            return flag;
        }
    
        private int getHight(TreeNode root){
            if(root == null){
                return 0;
            }
            int left = getHight(root.left);
            int right = getHight(root.right);
        
            if(Math.abs(left - right) > 1){
                flag = false;
            }
        
            return (left > right ? left : right) + 1;
        }
}

求二叉树中序遍历的下一个节点

分析:

1.二叉树为空,则返回空;

2.节点右孩子存在,则设置一个指针从该节点的右孩子出发,一直沿着指向左子结点的指针找到的叶子节点即为下一个节点;

3.节点不是根节点。如果该节点是其父节点的左孩子,则返回父节点;否则继续向上遍历其父节点的父节点,重复之前的判断,返回结果。 

实现代码:

public class Solution {
	public TreeLinkNode GetNext(TreeLinkNode pNode){
		if(pNode == null) {
			return null;
		}
		
		if(pNode.right != null) {
			pNode = pNode.right;
			while(pNode.left != null) {
				pNode = pNode.left;
			}
			return pNode;
		}
		
		while(pNode.next != null) {
			if(pNode.next.left == pNode) {
				return pNode.next;
			}
			pNode = pNode.next;
		}
        return null;
    }
}

给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。

分析:

本题给定了两个重要条件:① 树为 二叉搜索树 ,② 树的所有节点的值都是 唯一 的。根据以上条件,可方便地判断 p,q 与 root 的子树关系,即:

若 root.val < p.val,则 p 在 root 右子树 中;
若 root.val > p.val,则 p 在 root 左子树 中;
若 root.val = p.val,则 p 和 root 指向 同一节点 。

循环搜索: 当节点 root 为空时跳出;
当 p, q 都在 root 的 右子树 中,则遍历至 root.right;
否则,当 p, q 都在 root 的 左子树 中,则遍历至 root.left;
否则,说明找到了 最近公共祖先 ,跳出。
返回值: 最近公共祖先 root。

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

        //迭代循环
        while (root != null) {
            if (root.val < p.val && root.val < q.val) {
                root = root.right;
            } else if (root.val > p.val && root.val > q.val) {
                root = root.left;
            } else {
                return root;
            }
        }
        return null;

        //递归
        if (root.val < p.val && root.val < q.val) {
            return lowestCommonAncestor(root.right, p, q);
        } else if (root.val > p.val && root.val > q.val) {
            return lowestCommonAncestor(root.left, p, q);
        }
        return root;
    }
}

二叉树的中序遍历

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        Stack<TreeNode> stk = new Stack<TreeNode>();
        while (root != null || !stk.isEmpty()) {
            while (root != null) {
                stk.push(root);
                root = root.left;
            }
            root = stk.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }
}

(1)非递归定义 树(tree)是由n(n≥0)个结点组成的有限集合。n=0的树称为空树;n>0的树T: ① 有且仅有一个结点n0,它没有前驱结点,只有后继结点。n0称作树的根(root)结点。 ② 除结点外n0 , 其余的每一个结点都有且仅有一个直接前驱结点;有零个或多个直接后继结点。 (2)递归定义 一颗大树分成几个大的分枝,每个大分枝再分成几个小分枝,小分枝再分成更小的分枝,… ,每个分枝也都是一颗树,由此我们可以给出树的递归定义。 树(tree)是由n(n≥0)个结点组成的有限集合。n=0的树称为空树;n>0的树T: ① 有且仅有一个结点n0,它没有前驱结点,只有后继结点。n0称作树的根(root)结点。 ② 除根结点之外的其他结点分为m(m≥0)个互不相交的集合T0,T1,…,Tm-1,其中每个集合Ti(0≤i<m)本身又是一棵树,称为根的子树(subtree)。 2、掌握树的各种术语: (1) 父母、孩子与兄弟结点 (2) 度 (3) 结点层次、树的高度 (4) 边、路径 (5) 无序树、有序树 (6) 森林 3、二叉树的定义 二叉树(binary tree)是由n(n≥0)个结点组成的有限集合,此集合或者为空,或者由一个根结点加上两棵分别称为左、右子树的,互不相交的二叉树组成。 二叉树可以为空集,因此根可以有空的左子树或者右子树,亦或者左、右子树皆为空。 4、掌握二叉树的五个性质 5、二叉树二叉链表存储。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值