剑指offer(三十八):二叉树的深度
作者:互联网
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。 思路:本题可以使用递归和非递归两种算法,非递归可以使用层次遍历 C++递归实现:class Solution { public: int TreeDepth(TreeNode* pRoot) { if(!pRoot) return 0; int leftHigh = TreeDepth(pRoot->left)+1; int rightHigh = TreeDepth(pRoot->right)+1; int high = leftHigh>rightHigh?leftHigh:rightHigh; return high; } };
java层次遍历实现:
import java.util.*; public class Solution { public int TreeDepth(TreeNode root) { if(root == null) return 0; Queue<TreeNode> treeQ = new LinkedList<>(); Queue<Integer> highQ = new LinkedList<>(); TreeNode p; int high = 1; treeQ.add(root); highQ.add(high); while(!treeQ.isEmpty()){ p = treeQ.poll(); if(p!=null){ high = highQ.poll(); if(p.left != null){ treeQ.add(p.left); highQ.add(high+1); } if(p.right != null){ treeQ.add(p.right); highQ.add(high+1); } } } return high; } }
标签:return,三十八,offer,int,treeQ,high,highQ,add,二叉树 来源: https://www.cnblogs.com/ttzz/p/13449468.html