ffind二叉搜索树的叶节点

时间:2017-02-16 18:15:31

标签: binary-search-tree

我在面试问题中被问到,在preorder遍历二叉搜索树的情况下,找出叶节点而不构建原始树。我知道binary search tree必须满足的属性,但我无法找到与如何利用此属性完成任何关系。我唯一可以识别的是,first node中的preorder traversal将永远是根。谷歌搜索也没有产生这个问题的任何结果。我不希望代码只是一个简单的提示开始就足够了。

编辑:经过大量尝试后,我得到了这个解决方案:

#include<iostream>
#include<vector>
#include<string>
using namespace std;

void fl(vector<int> &v, int lo, int hi){
  if (lo>hi) return;
  if (lo == hi) { cout<<"leaf ^^^^^^^ "<< v[hi]<<"\n"; return; }
  int root = v[lo];
  int i;
  for(i = lo+1 ; i <= hi ; i++) if (v[i] > root) break;
  fl(v, lo+1, i -1);
  fl(v, i , hi);
}

int main(){
vector<int> v1 = {8, 3, 1, 6, 4, 7, 10, 14, 13};
vector<int> v2 = {27, 14, 10, 19, 35, 31, 42};
vector<int> v3 = {9,8,7,6,5,4,3,2,1};
fl(v3,0,v3.size()-1);
return 0;
}

除了变量名之外的任何改进建议都会非常有用

2 个答案:

答案 0 :(得分:0)

该程序应该从BST的preOrder打印叶节点。该计划非常自我解释。

public static void findLeafs(int[] arr) {
        if (arr == null || arr.length == 0)
            return;

        Stack<Integer> stack = new Stack<>();
        for(int n = 1, c = 0; n < arr.length; n++, c++) {
            if (arr[c] > arr[n]) {
                stack.push(arr[c]);
            } else {
                boolean found = false;
                while(!stack.isEmpty()) {

                    if (arr[n] > stack.peek()) {
                        stack.pop();
                        found = true;
                    } else 
                        break;      
                }
                if (found) 
                    System.out.println(arr[c]); 
            }

        }
        System.out.println(arr[arr.length-1]);
    }

答案 1 :(得分:0)

def getLeafNodes(data):
    if data:
        root=data[0]
        leafNodes=[]
        process(data[1:],root,leafNodes)
        return leafNodes

def process(data,root,leafNodes):
    if data:
        left=[]
        right=[]
        for i in range(len(data)):
            if data[i]<root: 
                left.append(data[i])
            if data[i]>root:
                right.append(data[i])

        if len(left)==0 and len(right)==0:
            leafNodes.append(root)
            return
        if len(left)>0:
            process(left[1:],left[0],leafNodes)
        if len(right)>0:
            process(right[1:],right[0],leafNodes)
    else:
        leafNodes.append(root)

#--Run--
print getLeafNodes([890,325,290,530,965])