解法一:非递归 vector<int> preorderTraversal(TreeNode* root) { vector<int> res; if (root == NULL) return res; stack<TreeNode*> node_stack; TreeNode *p = root; while (p || !node_stack.empty()) { if (p) { res.push_back(p->val); node_stack.push…
解法一:From top to bottom int treeHeight(TreeNode *T) { if (T == NULL) ; ; } bool isBalanced(TreeNode* root) { if (root == NULL) return true; int left_height = treeHeight(root->left); int right_height = treeHeight(root->right); ) return false; if (!isB…
解法一:递归 bool isSameTree(TreeNode* p, TreeNode* q) { if (p == NULL && q == NULL) return true; if ((p == NULL && q != NULL) || (p != NULL && q == NULL)) return false; if (p->val != q->val) return false; if (!isSameTree(p->lef…
199. 二叉树的右视图 199. Binary Tree Right Side View 题目描述 给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值. Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. LeetCode19…
Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 错误的思路(o(N2)时间复杂度): 写一个函数a,用递归遍历的方法,…
解法一:递归 int maxDepth(TreeNode* root) { if (root == NULL) ; int max_left_Depth = maxDepth(root->left); int max_right_Depth = maxDepth(root->right); ; } 解法二:BFS int maxDepth(TreeNode* root) { if (root == NULL) ; queue<TreeNode*> node_queue; node_…
解法一:递归 int minDepth(TreeNode* root) { if (root == NULL) ; if (root->left == NULL) { ; } else if (root->right == NULL) { ; } else { int left_minDepth = minDepth(root->left); int right_minDepth = minDepth(root->right); : right_minDepth + ; } } 解…
判断一棵树是否是平衡树,即左右子树的深度相差不超过1. 我们可以回顾下depth函数其实是Leetcode 104 Maximum Depth of Binary Tree 二叉树 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL…
Balanced Binary Tree [数据结构和算法]全面剖析树的各类遍历方法 描述 解析 递归分别判断每个节点的左右子树 该题是Easy的原因是该题可以很容易的想到时间复杂度为O(n^2)的方法.即按照定义,判断根节点左右子树的高度是不是相差1,递归判断左右子树是不是平衡的. 根据深度判断左右子树是否平衡 在计算树的高度的同时判断该树是不是平衡的. 即,先判断子树是不是平衡的,若是,则返回子树的高度:若不是,则返回一个非法的数字,如负数. 当一个节点是左右子树有一个不是平衡二叉树则不必继…
题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more tha…