問題:給一個二叉樹,寫一個算法判斷這個樹是不是balanced。 Solution #1. 第一次遇到這個問題時我的解法,如下: 寫了一個getDepth()函數,訪問每個節點都要調用一次這個函數。這個Solution也通過了leetcode的驗證程序,但是后來想了想,I ...
原題地址:http: oj.leetcode.com problems balanced binary tree 題意:判斷一顆二叉樹是否是平衡二叉樹。 解題思路:在這道題里,平衡二叉樹的定義是二叉樹的任意節點的兩顆子樹之間的高度差小於等於 。這實際上是AVL樹的定義。首先要寫一個計算二叉樹高度的函數,二叉樹的高度定義為:樹為空時,高度為 。然后遞歸求解:樹的高度 max 左子樹高度,右子樹高度 ...
2014-05-10 10:54 0 5388 推薦指數:
問題:給一個二叉樹,寫一個算法判斷這個樹是不是balanced。 Solution #1. 第一次遇到這個問題時我的解法,如下: 寫了一個getDepth()函數,訪問每個節點都要調用一次這個函數。這個Solution也通過了leetcode的驗證程序,但是后來想了想,I ...
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 ...
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 ...
Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree ...
for binary tree * struct TreeNode { * int val; ...
原題地址:http://oj.leetcode.com/problems/binary-tree-inorder-traversal/ 題意:二叉樹的中序遍歷。這道題用遞歸比較簡單,考察的是非遞歸實現二叉樹中序遍歷。中序遍歷順序為:左子樹,根,右子樹。如此遞歸下去。 解題思路:假設樹為: 1 / \ ...
原題地址:http://oj.leetcode.com/problems/binary-tree-preorder-traversal/ 題意:這題用遞歸比較簡單。應該考察的是使用非遞歸實現二叉樹的先序遍歷。先序遍歷的遍歷順序是:根,左子樹,右子樹。 解題思路:如果樹為下圖: 1 / \ ...
原題地址:http://oj.leetcode.com/problems/binary-tree-postorder-traversal/ 題意:實現后序遍歷。遞歸實現比較簡單,非遞歸實現。 解題思路:這道題的迭代求解比先序遍歷和后序遍歷要麻煩一些。假設一棵樹是這樣的: 1 / \ ...