以下三題都是關於二叉樹深度的問題
題目1:輸入一棵二叉樹,求該樹的深度(最大)。
注意:從根結點到葉結點依次經過的結點(含根、葉結點),形成樹的一條路徑,最長路徑的長度爲樹的深度
解析:
1.遞歸(左右子樹的最大深度+1即爲此二叉樹的深度)
public int TreeDepth(TreeNode root) {
if (root == null) return 0;
int leftDepth = 0, rightDepth = 0;
//加1是算上根節點
leftDepth = 1+TreeDepth(root.left);//左子樹的最大深度
rightDepth = 1+TreeDepth(root.right);//右子樹的最大深度
return Math.max(leftDepth, rightDepth);
}
2.非遞歸
類似於非遞歸後序遍歷中的做法。具體見代碼:
public int TreeDepth1(TreeNode root) {
if (root == null) return 0;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
//countDepth記錄迭代過程中樹的深度
//maxDepth二叉樹的最大深度
int countDepth = 1, maxDepth = 0;
TreeNode node = null;
while (root!=null||!stack.isEmpty()){
while (root!= null){
stack.push(root);
root = root.left;
countDepth++;
}
TreeNode curnode = stack.peek();
//當前結點沒有右孩子,或該節點右孩子被訪問過,回退一個節點
if (curnode.right==null||curnode.right==node){
stack.pop();
node = curnode;
root = null;
countDepth--;
}else{
root = curnode.right;
}
maxDepth = Math.max(maxDepth, countDepth);
}
return maxDepth;
}
題目2:輸入一棵二叉樹,求該樹的最小深度(最小深度是根節點到葉子結點)
解析:這裏有個小坑,就是沒有左子樹或沒有右子樹的時候,最小深度爲左子樹的深度或右子樹的深度
①如果根節點沒有左子樹,則其最小深度爲右子樹的最小深度;
②如果根節點沒有右子樹,則其最小深度爲左子樹的最小深度;
③如果根節點均有左子樹和右子樹,那麼最小深度爲左子樹和右子樹中最小的深度;
public int MinTreeDepth(TreeNode root) {
if (root == null) return 0;
int leftDepth = 0, rightDepth = 0;
if (root.left==null&&root.right!=null){
return 1+MinTreeDepth(root.right);
}else if(root.right==null&&root.left!=null){
return 1+MinTreeDepth(root.left);
}else{
return Math.min(1+MinTreeDepth(root.right), 1+MinTreeDepth(root.left));
}
}
題目3:輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。
解析:左右子樹的高度差的絕對值不超過1 左子樹 右子樹均是平衡二叉樹
①先計算左子樹的最大深度(左子樹的高度)和右子樹的最大深度(右子樹的最大深度);
②如果左子樹與右子樹中深度差大於1,則不爲平衡二叉樹;
③分別判斷左子樹和右子樹是否滿足依然爲平衡二叉樹,如果滿足則整棵二叉樹爲平衡二叉樹,如果不滿足則整棵二叉樹爲非平衡二叉樹;
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null) return true;
int leftDepth = DepthTree(root.left);
int rigthDepth = DepthTree(root.right);
if (Math.abs(leftDepth-rigthDepth)>1){
//如果左右子樹的高度差不滿足條件,則爲非平衡二叉樹
return false;
}else{
if (IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.left)){
//在滿足左右二叉樹的高度差絕對值不超過1且左右二叉樹均爲平衡二叉樹的條件下,整個二叉樹纔是平衡二叉樹
return true;
}else{
//如果左右子樹其中一個爲非平衡二叉樹,則整個二叉樹爲非平衡二叉樹
return false;
}
}
}
//求以該節點爲根節點的樹的最大深度
public int DepthTree(TreeNode node){
if (node==null) return 0;
return Math.max(1+DepthTree(node.left), 1+DepthTree(node.right));
}