由前序遍歷和中序遍歷重建二叉樹;
判斷一棵樹是否是完全二叉樹;
求二叉樹兩個節點的最近公共祖先;
將二叉搜尋樹轉換成乙個排序的雙向鍊錶。要求不能建立任何新的結點,只能調整樹中結點指標的指向。
//前序序列:1 2 3 4 5 6 - 中序序列:3 2 4 1 6 5
//在沒有重複節點的前提下
node* _greattree(int* prestart, int* preend,int* inarrstart,int* inarrend)
若設二叉樹的深度為h,除第 h 層外,其它各層 (1~h-1) 的結點數都達到最大個數,第 h 層所有的結點都連續集中在最左邊,這就是完全二叉樹。
完全二叉樹是由滿二叉樹而引出來的。對於深度為k的,有n個結點的二叉樹,當且僅當其每乙個結點都與深度為k的滿二叉樹中編號從1至n的結點一一對應時稱之為完全二叉樹。
一棵二叉樹至多只有最下面的一層上的結點的度數可以小於2,並且最下層上的結點都集中在該層最左邊的若干位置上,則此二叉樹成為完全二叉樹。
bool iscompletetreetwo(node* root)
return
true;
}
bool iscompletetree(node* root)
//此時應該是完全二叉樹的結尾;
//此時正確的情況應該是佇列中的所有元素都是null,否則不是完全二叉樹
while(!q.empty())
return
true;
}
//查詢最小公共祖先
int mincommonancestor(int x,int y)
//比兩個目標節點的值都小,繼續往右子樹找;
else
if(cur->_data < x && cur->_data < y)
//符合條件找到目標節點
else
if(cur->_data >= x && cur->_data <= y || cur->_data <= x && cur->_data >= y)
}}
//查詢最小公共祖先
int mincommonancestor(int x,int y)
++count1;
}cur = _root;
while(cur)
++count2;
}//求出長度差
int len = abs(count1 - count2);
if(count1 >= count2)
return _findfirstnode(nodeone,nodetwo,len);
else
return _findfirstnode(nodeone,nodetwo,len);
}int _findfirstnode(node* one,node* two, int len)
return one->_data;
}
int mincommonancestor(int x,int y)
node* _mincommonancestor(node* root,const
int x, const
int y)
//利用遞迴和棧儲存路徑,然後消去兩條路徑的差值,進行同時pop();找到第一對不同;
int mincommonancestor(int x,int y)
int count = s2.size() - s1.size();
return findcommonparent(s2,s1,count)->_data;
}node* findcommonparent(stack
first,stack
second,int count)
return first.top();
}bool _mincommonancestor(node* root,stack
& s, const
int x)
s.push(root);
bool left = _mincommonancestor(root->_left,s,x);
bool right = _mincommonancestor(root->_right,s,x);
if(left == false && right == false)
return
true;
}
node* turntolist()
void _turntolist(node* root, node*& prev)
二叉樹相關題
1 有父指標。分兩種情況 node findnextnode node node 2 右子樹為空,順著父指標往上找,直到找到乙個節點是其父節點的左孩子,則這個父節點就是下乙個節點 else next parent return next 2 普通二叉樹,借助中序遍歷 查詢中序遍歷的某個節點的下乙個節...
程式設計題 二叉樹
時間限制 3秒 空間限制 32768k 有一棵二叉樹,樹上每個點標有權值,權值各不相同,請設計乙個演算法算出權值最大的葉節點到權值最小的葉節點的距離。二叉樹每條邊的距離為1,乙個節點經過多少條邊到達另乙個節點為這兩個節點之間的距離。給定二叉樹的根節點root,請返回所求距離。強調一點 我就是被卡在這...
重建二叉樹 程式設計題
題目 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建該二叉樹,假設輸入的前序遍歷和中序遍歷的結果中都不含有重複值。前序遍歷 中序遍歷 主要思路 1.前序遍歷的第乙個元素是根節點,將根初始化。2.在中序遍歷中找到根的位置,根的左邊是左子樹,右邊是右子樹。3.然後左右遞迴。btnode reconstr...