剑指offer-二叉树的深度C++实现

剑指offer-二叉树的深度C++实现

原题链接

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
    
    
public:
    int TreeDepth(TreeNode* root) {
    
    
    // 根节点为叶子节点,返回0
    if (!root)return 0;
    	// 先遍历左子树,再遍历右子树
        int lf = TreeDepth(root->left);
        int rh = TreeDepth(root->right);
        // 左右子树最大值+1
        return max(lf, rh) + 1;
    }
};

思路:
这是一道DFS的题,主要实现是后序遍历+回溯,先遍历树的左子树,再遍历树的右子树,当根节点为叶子节点时,返回0,回溯时,取左右子树的最大值+1。

猜你喜欢

转载自blog.csdn.net/qq_35140742/article/details/121567811